farseer-cli 1.0.10 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +405 -400
  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 +453 -487
  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,431 @@
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}`);
131
- }
132
- currentId = folder.id;
133
- }
134
- if (currentId === null) {
135
- throw new Error('Path is empty');
136
- }
137
- // Return a minimal FolderItem with the found id
138
- return { id: currentId, name: path[path.length - 1], type: 'folder' };
139
- }
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
- }
74
+ const refreshed = await (0, import_farseerService.refreshAccessToken)(auth.refreshToken, auth.realm || "master");
75
+ if (!refreshed) {
76
+ throw new Error("Token refresh failed");
159
77
  }
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
+ }
160
95
  }
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;
175
- }
176
- async getFileContent(reference) {
177
- const response = await this.client.get(`/farseerFiles/${reference}`, {
178
- responseType: 'text',
179
- });
180
- return response.data;
181
- }
182
- async getFileContentAsBuffer(reference) {
183
- const response = await this.client.get(`/farseerFiles/${reference}`, {
184
- responseType: 'arraybuffer',
185
- });
186
- return Buffer.from(response.data);
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;
187
112
  }
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
- });
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;
211
124
  }
212
- async deleteFile(reference) {
213
- await this.client.delete(`/farseerFiles/${reference}`);
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;
214
145
  }
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
- }
233
- }
146
+ if (currentId === null) {
147
+ throw new Error("Path is empty");
234
148
  }
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
- }
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
+ });
254
168
  }
255
- catch {
256
- return null;
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
+ );
257
182
  }
258
- return null;
183
+ }
184
+ return [];
259
185
  }
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;
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
+ });
280
242
  }
243
+ }
281
244
  }
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);
285
- }
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 [];
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
+ };
305
261
  }
306
- return this.listAppsRecursive(appsFolderId);
262
+ }
263
+ } catch {
264
+ return null;
307
265
  }
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
- }
330
- }
331
- return apps;
332
- }
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
+ return response.data;
345
+ } catch {
346
+ return null;
386
347
  }
387
- /**
388
- * Delete an app
389
- */
390
- async deleteApp(referenceId) {
391
- await this.client.delete(`/remoteJobs/${referenceId}`);
392
- }
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;
348
+ }
349
+ /**
350
+ * Get app by name
351
+ */
352
+ async getAppByName(name) {
353
+ const apps = await this.listApps();
354
+ const app = apps.find((a) => a.name.toLowerCase() === name.toLowerCase());
355
+ if (!app) {
356
+ return null;
401
357
  }
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
- }));
358
+ return this.getApp(app.reference);
359
+ }
360
+ /**
361
+ * Create a new app
362
+ */
363
+ async createApp(name) {
364
+ const appsFolderId = await this.getAppsFolderId();
365
+ if (!appsFolderId) {
366
+ throw new Error("Apps folder not found");
415
367
  }
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;
368
+ const response = await this.client.post("/remoteJobs", {
369
+ folderId: appsFolderId,
370
+ name
371
+ });
372
+ return response.data;
373
+ }
374
+ /**
375
+ * Update an app
376
+ */
377
+ async updateApp(referenceId, update) {
378
+ await this.client.put(`/remoteJobs/${referenceId}`, {
379
+ ...update,
380
+ schedule: null,
381
+ runnerName: null,
382
+ predefinedActions: []
383
+ });
384
+ const app = await this.getApp(referenceId);
385
+ if (!app) {
386
+ throw new Error("Failed to fetch updated app");
424
387
  }
388
+ return app;
389
+ }
390
+ /**
391
+ * Delete an app
392
+ */
393
+ async deleteApp(referenceId) {
394
+ await this.client.delete(`/remoteJobs/${referenceId}`);
395
+ }
396
+ /**
397
+ * Run an app with arguments
398
+ */
399
+ async runApp(referenceId, args = {}) {
400
+ const response = await this.client.post(`/remoteJobs/${referenceId}/run`, {
401
+ arguments: args
402
+ });
403
+ return response.data;
404
+ }
405
+ /**
406
+ * Get script files available for apps (searches all .ts/.js files in Files folder)
407
+ * Returns full path relative to Files/ folder (e.g., "Scripts/test.ts", "Scripts/subfolder/helper.ts")
408
+ */
409
+ async getScriptFiles() {
410
+ const allFiles = await this.listFiles(["Files"]);
411
+ return allFiles.filter((f) => f.name.endsWith(".ts") || f.name.endsWith(".js")).map((f) => ({
412
+ id: f.reference,
413
+ name: f.path
414
+ // Use full path to support scripts in subfolders
415
+ }));
416
+ }
417
+ // ==================== Model Export API ====================
418
+ /**
419
+ * Export the entire model structure - all dimension tables, variables, and configurations.
420
+ * Essential for understanding a tenant's data model.
421
+ */
422
+ async exportModel() {
423
+ const response = await this.client.post("/model/export");
424
+ return response.data;
425
+ }
425
426
  }
426
- exports.FarseerApi = FarseerApi;
427
+ // Annotate the CommonJS export names for ESM import in node:
428
+ 0 && (module.exports = {
429
+ FarseerApi
430
+ });
431
+ //# sourceMappingURL=farseerApi.js.map