farseer-cli 1.0.10 → 1.1.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 (98) hide show
  1. package/README.md +19 -0
  2. package/dist/commands/app.js +348 -344
  3. package/dist/commands/app.js.map +7 -0
  4. package/dist/commands/apps.js +110 -82
  5. package/dist/commands/apps.js.map +7 -0
  6. package/dist/commands/cells.js +161 -0
  7. package/dist/commands/cells.js.map +7 -0
  8. package/dist/commands/checkout.js +140 -155
  9. package/dist/commands/checkout.js.map +7 -0
  10. package/dist/commands/config.js +128 -126
  11. package/dist/commands/config.js.map +7 -0
  12. package/dist/commands/dashboards.js +130 -0
  13. package/dist/commands/dashboards.js.map +7 -0
  14. package/dist/commands/diff.js +171 -193
  15. package/dist/commands/diff.js.map +7 -0
  16. package/dist/commands/dimensions.js +222 -119
  17. package/dist/commands/dimensions.js.map +7 -0
  18. package/dist/commands/files.js +96 -77
  19. package/dist/commands/files.js.map +7 -0
  20. package/dist/commands/formula.js +116 -0
  21. package/dist/commands/formula.js.map +7 -0
  22. package/dist/commands/install.js +74 -76
  23. package/dist/commands/install.js.map +7 -0
  24. package/dist/commands/list.js +91 -73
  25. package/dist/commands/list.js.map +7 -0
  26. package/dist/commands/login.js +137 -98
  27. package/dist/commands/login.js.map +7 -0
  28. package/dist/commands/logout.js +59 -41
  29. package/dist/commands/logout.js.map +7 -0
  30. package/dist/commands/mcp-server.js +36 -23
  31. package/dist/commands/mcp-server.js.map +7 -0
  32. package/dist/commands/model.js +186 -175
  33. package/dist/commands/model.js.map +7 -0
  34. package/dist/commands/pull.js +264 -274
  35. package/dist/commands/pull.js.map +7 -0
  36. package/dist/commands/push.js +209 -221
  37. package/dist/commands/push.js.map +7 -0
  38. package/dist/commands/run.js +276 -321
  39. package/dist/commands/run.js.map +7 -0
  40. package/dist/commands/sheets.js +200 -0
  41. package/dist/commands/sheets.js.map +7 -0
  42. package/dist/commands/status.js +149 -169
  43. package/dist/commands/status.js.map +7 -0
  44. package/dist/commands/variables.js +247 -188
  45. package/dist/commands/variables.js.map +7 -0
  46. package/dist/commands/whoami.js +65 -44
  47. package/dist/commands/whoami.js.map +7 -0
  48. package/dist/index.js +179 -115
  49. package/dist/index.js.map +7 -0
  50. package/dist/mcp/index.js +33 -16
  51. package/dist/mcp/index.js.map +7 -0
  52. package/dist/mcp/prompts/workflows.js +191 -145
  53. package/dist/mcp/prompts/workflows.js.map +7 -0
  54. package/dist/mcp/resources/documentation.js +158 -148
  55. package/dist/mcp/resources/documentation.js.map +7 -0
  56. package/dist/mcp/server.js +56 -33
  57. package/dist/mcp/server.js.map +7 -0
  58. package/dist/mcp/tools/appTools.js +309 -277
  59. package/dist/mcp/tools/appTools.js.map +7 -0
  60. package/dist/mcp/tools/authTools.js +130 -121
  61. package/dist/mcp/tools/authTools.js.map +7 -0
  62. package/dist/mcp/tools/cellTools.js +148 -0
  63. package/dist/mcp/tools/cellTools.js.map +7 -0
  64. package/dist/mcp/tools/dashboardTools.js +133 -0
  65. package/dist/mcp/tools/dashboardTools.js.map +7 -0
  66. package/dist/mcp/tools/dataTools.js +270 -267
  67. package/dist/mcp/tools/dataTools.js.map +7 -0
  68. package/dist/mcp/tools/modelTools.js +575 -229
  69. package/dist/mcp/tools/modelTools.js.map +7 -0
  70. package/dist/mcp/tools/runTools.js +201 -203
  71. package/dist/mcp/tools/runTools.js.map +7 -0
  72. package/dist/mcp/tools/sheetTools.js +240 -0
  73. package/dist/mcp/tools/sheetTools.js.map +7 -0
  74. package/dist/mcp/tools/syncTools.js +335 -314
  75. package/dist/mcp/tools/syncTools.js.map +7 -0
  76. package/dist/mcp/utils/helpers.js +117 -123
  77. package/dist/mcp/utils/helpers.js.map +7 -0
  78. package/dist/services/appSyncService.js +381 -437
  79. package/dist/services/appSyncService.js.map +7 -0
  80. package/dist/services/configService.js +154 -143
  81. package/dist/services/configService.js.map +7 -0
  82. package/dist/services/farseerApi.js +422 -399
  83. package/dist/services/farseerApi.js.map +7 -0
  84. package/dist/services/farseerFactory.js +208 -273
  85. package/dist/services/farseerFactory.js.map +7 -0
  86. package/dist/services/farseerService.js +467 -486
  87. package/dist/services/farseerService.js.map +7 -0
  88. package/dist/services/syncService.js +661 -731
  89. package/dist/services/syncService.js.map +7 -0
  90. package/dist/utils/constants.js +52 -19
  91. package/dist/utils/constants.js.map +7 -0
  92. package/dist/utils/entityResolver.js +78 -0
  93. package/dist/utils/entityResolver.js.map +7 -0
  94. package/dist/utils/helpers.js +331 -365
  95. package/dist/utils/helpers.js.map +7 -0
  96. package/dist/utils/logger.js +74 -42
  97. package/dist/utils/logger.js.map +7 -0
  98. package/package.json +3 -2
@@ -1,426 +1,449 @@
1
1
  "use strict";
2
- /**
3
- * FarseerApi - Direct HTTP API client using JWT Bearer token authentication
4
- *
5
- * This is an alternative to FarseerService that doesn't use farseer-client library.
6
- * Use this when authenticating via browser login (Keycloak JWT token) instead of API key.
7
- */
8
- var __importDefault = (this && this.__importDefault) || function (mod) {
9
- return (mod && mod.__esModule) ? mod : { "default": mod };
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
10
11
  };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.FarseerApi = void 0;
13
- const axios_1 = __importDefault(require("axios"));
14
- const configService_1 = require("./configService");
15
- const farseerService_1 = require("./farseerService");
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var farseerApi_exports = {};
30
+ __export(farseerApi_exports, {
31
+ FarseerApi: () => FarseerApi
32
+ });
33
+ module.exports = __toCommonJS(farseerApi_exports);
34
+ var import_axios = __toESM(require("axios"));
35
+ var import_configService = require("./configService");
36
+ var import_farseerService = require("./farseerService");
16
37
  class FarseerApi {
17
- constructor(accessToken, tenant, tenantId) {
18
- this.isRefreshing = false;
19
- this.refreshSubscribers = [];
20
- this.tenant = tenant;
21
- this.tenantId = tenantId || tenant;
22
- // Try to get basePath from existing config, or generate from tenant name
23
- const credential = (0, configService_1.getCredential)(tenant);
24
- const basePath = credential?.basePath || `https://${tenant}.farseer.io/api/v3`;
25
- this.client = axios_1.default.create({
26
- baseURL: basePath,
27
- headers: {
28
- Authorization: `Bearer ${accessToken}`,
29
- 'Content-Type': 'application/json',
30
- 'x-api-version': '3.3.0',
31
- 'X-TENANT-ID': this.tenantId,
32
- },
33
- });
34
- // Add response interceptor for automatic token refresh on 401
35
- this.client.interceptors.response.use((response) => response, async (error) => {
36
- const originalRequest = error.config;
37
- // Only handle 401 errors and avoid infinite loops
38
- if (error.response?.status === 401 && !originalRequest._retry) {
39
- originalRequest._retry = true;
40
- // If already refreshing, wait for the new token
41
- if (this.isRefreshing) {
42
- return new Promise((resolve) => {
43
- this.refreshSubscribers.push((token) => {
44
- originalRequest.headers['Authorization'] = `Bearer ${token}`;
45
- resolve(this.client(originalRequest));
46
- });
47
- });
48
- }
49
- this.isRefreshing = true;
50
- try {
51
- const auth = (0, configService_1.getUserAuth)();
52
- if (!auth?.refreshToken) {
53
- throw new Error('No refresh token available');
54
- }
55
- const refreshed = await (0, farseerService_1.refreshAccessToken)(auth.refreshToken, auth.realm || 'master');
56
- if (!refreshed) {
57
- throw new Error('Token refresh failed');
58
- }
59
- // Save the new token
60
- (0, configService_1.setUserAuth)({
61
- accessToken: refreshed.accessToken,
62
- refreshToken: refreshed.refreshToken,
63
- expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),
64
- realm: auth.realm,
65
- });
66
- // Update this client's token
67
- this.updateAccessToken(refreshed.accessToken);
68
- // Notify all waiting requests
69
- this.refreshSubscribers.forEach((callback) => callback(refreshed.accessToken));
70
- this.refreshSubscribers = [];
71
- // Retry the original request
72
- originalRequest.headers['Authorization'] = `Bearer ${refreshed.accessToken}`;
73
- return this.client(originalRequest);
74
- }
75
- catch (refreshError) {
76
- // Token refresh failed - let the error propagate
77
- this.refreshSubscribers = [];
78
- throw error;
79
- }
80
- finally {
81
- this.isRefreshing = false;
82
- }
38
+ constructor(accessToken, tenant, tenantId) {
39
+ this.isRefreshing = false;
40
+ this.refreshSubscribers = [];
41
+ this.tenant = tenant;
42
+ this.tenantId = tenantId || tenant;
43
+ const credential = (0, import_configService.getCredential)(tenant);
44
+ const basePath = credential?.basePath || `https://${tenant}.farseer.io/api/v3`;
45
+ this.client = import_axios.default.create({
46
+ baseURL: basePath,
47
+ headers: {
48
+ Authorization: `Bearer ${accessToken}`,
49
+ "Content-Type": "application/json",
50
+ "x-api-version": "3.3.0",
51
+ "X-TENANT-ID": this.tenantId
52
+ }
53
+ });
54
+ this.client.interceptors.response.use(
55
+ (response) => response,
56
+ async (error) => {
57
+ const originalRequest = error.config;
58
+ if (error.response?.status === 401 && !originalRequest._retry) {
59
+ originalRequest._retry = true;
60
+ if (this.isRefreshing) {
61
+ return new Promise((resolve) => {
62
+ this.refreshSubscribers.push((token) => {
63
+ originalRequest.headers["Authorization"] = `Bearer ${token}`;
64
+ resolve(this.client(originalRequest));
65
+ });
66
+ });
67
+ }
68
+ this.isRefreshing = true;
69
+ try {
70
+ const auth = (0, import_configService.getUserAuth)();
71
+ if (!auth?.refreshToken) {
72
+ throw new Error("No refresh token available");
83
73
  }
84
- return Promise.reject(error);
85
- });
86
- }
87
- /**
88
- * Update the access token (used when token is refreshed)
89
- */
90
- updateAccessToken(newToken) {
91
- this.client.defaults.headers['Authorization'] = `Bearer ${newToken}`;
92
- }
93
- async testConnection() {
94
- try {
95
- await this.getItemByPath(['Files']);
96
- return true;
97
- }
98
- catch {
99
- return false;
100
- }
101
- }
102
- async getFilesFolder() {
103
- try {
104
- const item = await this.getItemByPath(['Files']);
105
- return {
106
- id: item.id,
107
- name: item.name,
108
- type: item.type,
109
- };
110
- }
111
- catch {
112
- return null;
113
- }
114
- }
115
- async listFolderItems(folderId) {
116
- // Body is array: [{ id: null }] for root, [{ id: folderId }] for specific folder
117
- const response = await this.client.post('/folders/items', [{ id: folderId }]);
118
- return response.data[0] || { items: [] };
119
- }
120
- async findFolderByName(parentId, name) {
121
- const content = await this.listFolderItems(parentId);
122
- const folder = content.items?.find((item) => item.name.toLowerCase() === name.toLowerCase() && item.type.toLowerCase() === 'folder');
123
- return folder || null;
124
- }
125
- async getItemByPath(path) {
126
- let currentId = null;
127
- for (const segment of path) {
128
- const folder = await this.findFolderByName(currentId, segment);
129
- if (!folder) {
130
- throw new Error(`Folder not found: ${segment}`);
74
+ const refreshed = await (0, import_farseerService.refreshAccessToken)(auth.refreshToken, auth.realm || "master");
75
+ if (!refreshed) {
76
+ throw new Error("Token refresh failed");
131
77
  }
132
- currentId = folder.id;
133
- }
134
- if (currentId === null) {
135
- throw new Error('Path is empty');
78
+ (0, import_configService.setUserAuth)({
79
+ accessToken: refreshed.accessToken,
80
+ refreshToken: refreshed.refreshToken,
81
+ expiresAt: new Date(Date.now() + refreshed.expiresIn * 1e3).toISOString(),
82
+ realm: auth.realm
83
+ });
84
+ this.updateAccessToken(refreshed.accessToken);
85
+ this.refreshSubscribers.forEach((callback) => callback(refreshed.accessToken));
86
+ this.refreshSubscribers = [];
87
+ originalRequest.headers["Authorization"] = `Bearer ${refreshed.accessToken}`;
88
+ return this.client(originalRequest);
89
+ } catch (refreshError) {
90
+ this.refreshSubscribers = [];
91
+ throw error;
92
+ } finally {
93
+ this.isRefreshing = false;
94
+ }
136
95
  }
137
- // Return a minimal FolderItem with the found id
138
- return { id: currentId, name: path[path.length - 1], type: 'folder' };
96
+ return Promise.reject(error);
97
+ }
98
+ );
99
+ }
100
+ /**
101
+ * Update the access token (used when token is refreshed)
102
+ */
103
+ updateAccessToken(newToken) {
104
+ this.client.defaults.headers["Authorization"] = `Bearer ${newToken}`;
105
+ }
106
+ async testConnection() {
107
+ try {
108
+ await this.getItemByPath(["Files"]);
109
+ return true;
110
+ } catch {
111
+ return false;
139
112
  }
140
- async listFiles(folderPath = ['Files']) {
141
- const files = [];
142
- try {
143
- const folder = await this.getItemByPath(folderPath);
144
- const folderContent = await this.listFolderItems(folder.id);
145
- for (const item of folderContent.items || []) {
146
- const itemPath = [...folderPath.slice(1), item.name].join('/');
147
- const itemType = item.type.toLowerCase();
148
- if (itemType === 'folder') {
149
- const subFiles = await this.listFiles([...folderPath, item.name]);
150
- files.push(...subFiles);
151
- }
152
- else if ((itemType === 'farseer-file' || itemType === 'farseer_file') && item.reference) {
153
- files.push({
154
- name: item.name,
155
- path: itemPath,
156
- reference: item.reference,
157
- });
158
- }
159
- }
160
- }
161
- catch (error) {
162
- if (axios_1.default.isAxiosError(error)) {
163
- const status = error.response?.status;
164
- const data = error.response?.data;
165
- const message = typeof data === 'string' ? data : data?.message || JSON.stringify(data);
166
- console.error(`API Error: ${status} "${message}" (path: ${folderPath.join('/')})`);
167
- if (data?.code === 'Forbidden') {
168
- const errorMessage = data?.message || 'Access denied';
169
- throw new Error(`Access denied: ${errorMessage}\nYou may need to use --tenant-id to specify a different tenant ID.`);
170
- }
171
- }
172
- return [];
173
- }
174
- return files;
113
+ }
114
+ async getFilesFolder() {
115
+ try {
116
+ const item = await this.getItemByPath(["Files"]);
117
+ return {
118
+ id: item.id,
119
+ name: item.name,
120
+ type: item.type
121
+ };
122
+ } catch {
123
+ return null;
175
124
  }
176
- async getFileContent(reference) {
177
- const response = await this.client.get(`/farseerFiles/${reference}`, {
178
- responseType: 'text',
179
- });
180
- return response.data;
125
+ }
126
+ async listFolderItems(folderId) {
127
+ const response = await this.client.post("/folders/items", [{ id: folderId }]);
128
+ return response.data[0] || { items: [] };
129
+ }
130
+ async findFolderByName(parentId, name) {
131
+ const content = await this.listFolderItems(parentId);
132
+ const folder = content.items?.find(
133
+ (item) => item.name.toLowerCase() === name.toLowerCase() && item.type.toLowerCase() === "folder"
134
+ );
135
+ return folder || null;
136
+ }
137
+ async getItemByPath(path) {
138
+ let currentId = null;
139
+ for (const segment of path) {
140
+ const folder = await this.findFolderByName(currentId, segment);
141
+ if (!folder) {
142
+ throw new Error(`Folder not found: ${segment}`);
143
+ }
144
+ currentId = folder.id;
181
145
  }
182
- async getFileContentAsBuffer(reference) {
183
- const response = await this.client.get(`/farseerFiles/${reference}`, {
184
- responseType: 'arraybuffer',
185
- });
186
- return Buffer.from(response.data);
146
+ if (currentId === null) {
147
+ throw new Error("Path is empty");
187
148
  }
188
- async createFile(content, fileName, folderPath = ['Files']) {
189
- await this.ensureFolderPath(folderPath);
190
- const folder = await this.getItemByPath(folderPath);
191
- const formData = new FormData();
192
- const blob = content instanceof Buffer ? new Blob([content]) : new Blob([content]);
193
- formData.append('file', blob, fileName);
194
- formData.append('category', 'GENERAL');
195
- formData.append('folderId', folder.id.toString());
196
- await this.client.post('/farseerFiles', formData, {
197
- headers: {
198
- 'Content-Type': 'multipart/form-data',
199
- },
200
- });
201
- }
202
- async updateFile(reference, content, fileName) {
203
- const formData = new FormData();
204
- const blob = content instanceof Buffer ? new Blob([content]) : new Blob([content]);
205
- formData.append('file', blob, fileName);
206
- await this.client.put(`/farseerFiles/${reference}`, formData, {
207
- headers: {
208
- 'Content-Type': 'multipart/form-data',
209
- },
210
- });
211
- }
212
- async deleteFile(reference) {
213
- await this.client.delete(`/farseerFiles/${reference}`);
214
- }
215
- async ensureFolderPath(folderPath) {
216
- const currentPath = [];
217
- for (const segment of folderPath) {
218
- currentPath.push(segment);
219
- try {
220
- await this.getItemByPath(currentPath);
221
- }
222
- catch {
223
- if (currentPath.length > 1) {
224
- const parentPath = currentPath.slice(0, -1);
225
- const parent = await this.getItemByPath(parentPath);
226
- await this.client.post('/folders', {
227
- parentId: parent.id,
228
- name: segment,
229
- allowedTypes: [],
230
- });
231
- }
232
- }
149
+ return { id: currentId, name: path[path.length - 1], type: "folder" };
150
+ }
151
+ async listFiles(folderPath = ["Files"]) {
152
+ const files = [];
153
+ try {
154
+ const folder = await this.getItemByPath(folderPath);
155
+ const folderContent = await this.listFolderItems(folder.id);
156
+ for (const item of folderContent.items || []) {
157
+ const itemPath = [...folderPath.slice(1), item.name].join("/");
158
+ const itemType = item.type.toLowerCase();
159
+ if (itemType === "folder") {
160
+ const subFiles = await this.listFiles([...folderPath, item.name]);
161
+ files.push(...subFiles);
162
+ } else if ((itemType === "farseer-file" || itemType === "farseer_file") && item.reference) {
163
+ files.push({
164
+ name: item.name,
165
+ path: itemPath,
166
+ reference: item.reference
167
+ });
233
168
  }
234
- }
235
- async getFileByPath(filePath) {
236
- const pathParts = ['Files', ...filePath.split('/')];
237
- const fileName = pathParts.pop();
238
- const folderPath = pathParts;
239
- try {
240
- const folder = await this.getItemByPath(folderPath);
241
- const folderContent = await this.listFolderItems(folder.id);
242
- for (const item of folderContent.items || []) {
243
- const itemType = item.type.toLowerCase();
244
- if (item.name === fileName &&
245
- (itemType === 'farseer-file' || itemType === 'farseer_file') &&
246
- item.reference) {
247
- return {
248
- name: item.name,
249
- path: filePath,
250
- reference: item.reference,
251
- };
252
- }
253
- }
169
+ }
170
+ } catch (error) {
171
+ if (import_axios.default.isAxiosError(error)) {
172
+ const status = error.response?.status;
173
+ const data = error.response?.data;
174
+ const message = typeof data === "string" ? data : data?.message || JSON.stringify(data);
175
+ console.error(`API Error: ${status} "${message}" (path: ${folderPath.join("/")})`);
176
+ if (data?.code === "Forbidden") {
177
+ const errorMessage = data?.message || "Access denied";
178
+ throw new Error(
179
+ `Access denied: ${errorMessage}
180
+ You may need to use --tenant-id to specify a different tenant ID.`
181
+ );
254
182
  }
255
- catch {
256
- return null;
257
- }
258
- return null;
259
- }
260
- async getFileMetadata(reference) {
261
- try {
262
- const response = await this.client.get(`/farseerFiles/${reference}/metadata`);
263
- const data = response.data;
264
- return {
265
- uploadTime: data.uploadTime,
266
- uploader: data.uploader
267
- ? {
268
- id: data.uploader.id,
269
- email: data.uploader.email || '',
270
- firstName: data.uploader.firstName || '',
271
- lastName: data.uploader.lastName || '',
272
- }
273
- : undefined,
274
- size: data.size,
275
- };
276
- }
277
- catch (error) {
278
- // Metadata fetch failed - non-critical, continue without it
279
- return null;
280
- }
281
- }
282
- isTextFile(filename) {
283
- const ext = filename.toLowerCase().split('.').pop() || '';
284
- return ['ts', 'js', 'mjs', 'cjs', 'json', 'txt', 'md', 'csv', 'xml', 'html', 'css', 'yaml', 'yml'].includes(ext);
183
+ }
184
+ return [];
285
185
  }
286
- isBinaryFile(filename) {
287
- return !this.isTextFile(filename);
288
- }
289
- // ==================== Apps (Remote Jobs) API ====================
290
- /**
291
- * Get the Apps folder ID
292
- */
293
- async getAppsFolderId() {
294
- const content = await this.listFolderItems(null);
295
- const appsFolder = content.items?.find((item) => item.name.toLowerCase() === 'apps' && item.type.toLowerCase() === 'folder');
296
- return appsFolder?.id || null;
297
- }
298
- /**
299
- * List all apps (Remote Jobs) on the tenant, including those in subfolders
300
- */
301
- async listApps() {
302
- const appsFolderId = await this.getAppsFolderId();
303
- if (!appsFolderId) {
304
- return [];
186
+ return files;
187
+ }
188
+ async getFileContent(reference) {
189
+ const response = await this.client.get(`/farseerFiles/${reference}`, {
190
+ responseType: "text"
191
+ });
192
+ return response.data;
193
+ }
194
+ async getFileContentAsBuffer(reference) {
195
+ const response = await this.client.get(`/farseerFiles/${reference}`, {
196
+ responseType: "arraybuffer"
197
+ });
198
+ return Buffer.from(response.data);
199
+ }
200
+ async createFile(content, fileName, folderPath = ["Files"]) {
201
+ await this.ensureFolderPath(folderPath);
202
+ const folder = await this.getItemByPath(folderPath);
203
+ const formData = new FormData();
204
+ const blob = content instanceof Buffer ? new Blob([content]) : new Blob([content]);
205
+ formData.append("file", blob, fileName);
206
+ formData.append("category", "GENERAL");
207
+ formData.append("folderId", folder.id.toString());
208
+ await this.client.post("/farseerFiles", formData, {
209
+ headers: {
210
+ "Content-Type": "multipart/form-data"
211
+ }
212
+ });
213
+ }
214
+ async updateFile(reference, content, fileName) {
215
+ const formData = new FormData();
216
+ const blob = content instanceof Buffer ? new Blob([content]) : new Blob([content]);
217
+ formData.append("file", blob, fileName);
218
+ await this.client.put(`/farseerFiles/${reference}`, formData, {
219
+ headers: {
220
+ "Content-Type": "multipart/form-data"
221
+ }
222
+ });
223
+ }
224
+ async deleteFile(reference) {
225
+ await this.client.delete(`/farseerFiles/${reference}`);
226
+ }
227
+ async ensureFolderPath(folderPath) {
228
+ const currentPath = [];
229
+ for (const segment of folderPath) {
230
+ currentPath.push(segment);
231
+ try {
232
+ await this.getItemByPath(currentPath);
233
+ } catch {
234
+ if (currentPath.length > 1) {
235
+ const parentPath = currentPath.slice(0, -1);
236
+ const parent = await this.getItemByPath(parentPath);
237
+ await this.client.post("/folders", {
238
+ parentId: parent.id,
239
+ name: segment,
240
+ allowedTypes: []
241
+ });
305
242
  }
306
- return this.listAppsRecursive(appsFolderId);
243
+ }
307
244
  }
308
- /**
309
- * Recursively list all apps in a folder and its subfolders
310
- */
311
- async listAppsRecursive(folderId) {
312
- const apps = [];
313
- const content = await this.listFolderItems(folderId);
314
- for (const item of content.items || []) {
315
- const itemType = item.type.toLowerCase();
316
- if (itemType === 'remote_job') {
317
- // Found an app
318
- apps.push({
319
- id: item.id,
320
- name: item.name,
321
- type: item.type,
322
- reference: item.reference || '',
323
- });
324
- }
325
- else if (itemType === 'folder') {
326
- // Recurse into subfolder
327
- const subApps = await this.listAppsRecursive(item.id);
328
- apps.push(...subApps);
329
- }
245
+ }
246
+ async getFileByPath(filePath) {
247
+ const pathParts = ["Files", ...filePath.split("/")];
248
+ const fileName = pathParts.pop();
249
+ const folderPath = pathParts;
250
+ try {
251
+ const folder = await this.getItemByPath(folderPath);
252
+ const folderContent = await this.listFolderItems(folder.id);
253
+ for (const item of folderContent.items || []) {
254
+ const itemType = item.type.toLowerCase();
255
+ if (item.name === fileName && (itemType === "farseer-file" || itemType === "farseer_file") && item.reference) {
256
+ return {
257
+ name: item.name,
258
+ path: filePath,
259
+ reference: item.reference
260
+ };
330
261
  }
331
- return apps;
262
+ }
263
+ } catch {
264
+ return null;
332
265
  }
333
- /**
334
- * Get app details by reference ID
335
- */
336
- async getApp(referenceId) {
337
- try {
338
- const response = await this.client.get(`/remoteJobs/${referenceId}`);
339
- return response.data;
340
- }
341
- catch {
342
- return null;
343
- }
266
+ return null;
267
+ }
268
+ async getFileMetadata(reference) {
269
+ try {
270
+ const response = await this.client.get(`/farseerFiles/${reference}/metadata`);
271
+ const data = response.data;
272
+ return {
273
+ uploadTime: data.uploadTime,
274
+ uploader: data.uploader ? {
275
+ id: data.uploader.id,
276
+ email: data.uploader.email || "",
277
+ firstName: data.uploader.firstName || "",
278
+ lastName: data.uploader.lastName || ""
279
+ } : void 0,
280
+ size: data.size
281
+ };
282
+ } catch (error) {
283
+ return null;
344
284
  }
345
- /**
346
- * Get app by name
347
- */
348
- async getAppByName(name) {
349
- const apps = await this.listApps();
350
- const app = apps.find((a) => a.name.toLowerCase() === name.toLowerCase());
351
- if (!app) {
352
- return null;
353
- }
354
- return this.getApp(app.reference);
285
+ }
286
+ isTextFile(filename) {
287
+ const ext = filename.toLowerCase().split(".").pop() || "";
288
+ return ["ts", "js", "mjs", "cjs", "json", "txt", "md", "csv", "xml", "html", "css", "yaml", "yml"].includes(
289
+ ext
290
+ );
291
+ }
292
+ isBinaryFile(filename) {
293
+ return !this.isTextFile(filename);
294
+ }
295
+ // ==================== Apps (Remote Jobs) API ====================
296
+ /**
297
+ * Get the Apps folder ID
298
+ */
299
+ async getAppsFolderId() {
300
+ const content = await this.listFolderItems(null);
301
+ const appsFolder = content.items?.find(
302
+ (item) => item.name.toLowerCase() === "apps" && item.type.toLowerCase() === "folder"
303
+ );
304
+ return appsFolder?.id || null;
305
+ }
306
+ /**
307
+ * List all apps (Remote Jobs) on the tenant, including those in subfolders
308
+ */
309
+ async listApps() {
310
+ const appsFolderId = await this.getAppsFolderId();
311
+ if (!appsFolderId) {
312
+ return [];
355
313
  }
356
- /**
357
- * Create a new app
358
- */
359
- async createApp(name) {
360
- const appsFolderId = await this.getAppsFolderId();
361
- if (!appsFolderId) {
362
- throw new Error('Apps folder not found');
363
- }
364
- const response = await this.client.post('/remoteJobs', {
365
- folderId: appsFolderId,
366
- name,
314
+ return this.listAppsRecursive(appsFolderId);
315
+ }
316
+ /**
317
+ * Recursively list all apps in a folder and its subfolders
318
+ */
319
+ async listAppsRecursive(folderId) {
320
+ const apps = [];
321
+ const content = await this.listFolderItems(folderId);
322
+ for (const item of content.items || []) {
323
+ const itemType = item.type.toLowerCase();
324
+ if (itemType === "remote_job") {
325
+ apps.push({
326
+ id: item.id,
327
+ name: item.name,
328
+ type: item.type,
329
+ reference: item.reference || ""
367
330
  });
368
- return response.data;
331
+ } else if (itemType === "folder") {
332
+ const subApps = await this.listAppsRecursive(item.id);
333
+ apps.push(...subApps);
334
+ }
369
335
  }
370
- /**
371
- * Update an app
372
- */
373
- async updateApp(referenceId, update) {
374
- await this.client.put(`/remoteJobs/${referenceId}`, {
375
- ...update,
376
- schedule: null,
377
- runnerName: null,
378
- predefinedActions: [],
379
- });
380
- // API returns 204 No Content, so fetch the updated app
381
- const app = await this.getApp(referenceId);
382
- if (!app) {
383
- throw new Error('Failed to fetch updated app');
384
- }
385
- return app;
336
+ return apps;
337
+ }
338
+ /**
339
+ * Get app details by reference ID
340
+ */
341
+ async getApp(referenceId) {
342
+ try {
343
+ const response = await this.client.get(`/remoteJobs/${referenceId}`);
344
+ const app = response.data;
345
+ if ((!app.scriptFiles || app.scriptFiles.length === 0) && app.sourceFolderId) {
346
+ app.scriptFiles = await this.resolveAppScripts(app.sourceFolderId);
347
+ }
348
+ return app;
349
+ } catch {
350
+ return null;
386
351
  }
387
- /**
388
- * Delete an app
389
- */
390
- async deleteApp(referenceId) {
391
- await this.client.delete(`/remoteJobs/${referenceId}`);
352
+ }
353
+ /**
354
+ * Resolve script files from an app's source folder
355
+ */
356
+ async resolveAppScripts(sourceFolderId) {
357
+ try {
358
+ const content = await this.listFolderItems(sourceFolderId);
359
+ return (content.items || []).filter((item) => {
360
+ const t = item.type.toLowerCase();
361
+ return (t === "farseer-file" || t === "farseer_file") && item.reference;
362
+ }).map((item) => ({ id: item.reference, name: item.name }));
363
+ } catch {
364
+ return [];
392
365
  }
393
- /**
394
- * Run an app with arguments
395
- */
396
- async runApp(referenceId, args = {}) {
397
- const response = await this.client.post(`/remoteJobs/${referenceId}/run`, {
398
- arguments: args,
399
- });
400
- return response.data;
366
+ }
367
+ /**
368
+ * Get app by name
369
+ */
370
+ async getAppByName(name) {
371
+ const apps = await this.listApps();
372
+ const app = apps.find((a) => a.name.toLowerCase() === name.toLowerCase());
373
+ if (!app) {
374
+ return null;
401
375
  }
402
- /**
403
- * Get script files available for apps (searches all .ts/.js files in Files folder)
404
- * Returns full path relative to Files/ folder (e.g., "Scripts/test.ts", "Scripts/subfolder/helper.ts")
405
- */
406
- async getScriptFiles() {
407
- // listFiles already searches recursively, so just filter for .ts/.js files
408
- const allFiles = await this.listFiles(['Files']);
409
- return allFiles
410
- .filter((f) => f.name.endsWith('.ts') || f.name.endsWith('.js'))
411
- .map((f) => ({
412
- id: f.reference,
413
- name: f.path, // Use full path to support scripts in subfolders
414
- }));
376
+ return this.getApp(app.reference);
377
+ }
378
+ /**
379
+ * Create a new app
380
+ */
381
+ async createApp(name) {
382
+ const appsFolderId = await this.getAppsFolderId();
383
+ if (!appsFolderId) {
384
+ throw new Error("Apps folder not found");
415
385
  }
416
- // ==================== Model Export API ====================
417
- /**
418
- * Export the entire model structure - all dimension tables, variables, and configurations.
419
- * Essential for understanding a tenant's data model.
420
- */
421
- async exportModel() {
422
- const response = await this.client.post('/model/export');
423
- return response.data;
386
+ const response = await this.client.post("/remoteJobs", {
387
+ folderId: appsFolderId,
388
+ name
389
+ });
390
+ return response.data;
391
+ }
392
+ /**
393
+ * Update an app
394
+ */
395
+ async updateApp(referenceId, update) {
396
+ await this.client.put(`/remoteJobs/${referenceId}`, {
397
+ ...update,
398
+ schedule: null,
399
+ runnerName: null,
400
+ predefinedActions: []
401
+ });
402
+ const app = await this.getApp(referenceId);
403
+ if (!app) {
404
+ throw new Error("Failed to fetch updated app");
424
405
  }
406
+ return app;
407
+ }
408
+ /**
409
+ * Delete an app
410
+ */
411
+ async deleteApp(referenceId) {
412
+ await this.client.delete(`/remoteJobs/${referenceId}`);
413
+ }
414
+ /**
415
+ * Run an app with arguments
416
+ */
417
+ async runApp(referenceId, args = {}) {
418
+ const response = await this.client.post(`/remoteJobs/${referenceId}/run`, {
419
+ arguments: args
420
+ });
421
+ return response.data;
422
+ }
423
+ /**
424
+ * Get script files available for apps (searches all .ts/.js files in Files folder)
425
+ * Returns full path relative to Files/ folder (e.g., "Scripts/test.ts", "Scripts/subfolder/helper.ts")
426
+ */
427
+ async getScriptFiles() {
428
+ const allFiles = await this.listFiles(["Files"]);
429
+ return allFiles.filter((f) => f.name.endsWith(".ts") || f.name.endsWith(".js")).map((f) => ({
430
+ id: f.reference,
431
+ name: f.path
432
+ // Use full path to support scripts in subfolders
433
+ }));
434
+ }
435
+ // ==================== Model Export API ====================
436
+ /**
437
+ * Export the entire model structure - all dimension tables, variables, and configurations.
438
+ * Essential for understanding a tenant's data model.
439
+ */
440
+ async exportModel() {
441
+ const response = await this.client.post("/model/export");
442
+ return response.data;
443
+ }
425
444
  }
426
- exports.FarseerApi = FarseerApi;
445
+ // Annotate the CommonJS export names for ESM import in node:
446
+ 0 && (module.exports = {
447
+ FarseerApi
448
+ });
449
+ //# sourceMappingURL=farseerApi.js.map