farseer-cli 1.10.2 → 1.11.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 (90) hide show
  1. package/README.md +7 -0
  2. package/dist/commands/app.js +15 -12
  3. package/dist/commands/app.js.map +2 -2
  4. package/dist/commands/apps.js +3 -3
  5. package/dist/commands/apps.js.map +2 -2
  6. package/dist/commands/cells.js +3 -3
  7. package/dist/commands/cells.js.map +2 -2
  8. package/dist/commands/config.js +23 -15
  9. package/dist/commands/config.js.map +2 -2
  10. package/dist/commands/dashboards.js +3 -3
  11. package/dist/commands/dashboards.js.map +2 -2
  12. package/dist/commands/dimensions.js +3 -3
  13. package/dist/commands/dimensions.js.map +2 -2
  14. package/dist/commands/files.js +5 -4
  15. package/dist/commands/files.js.map +2 -2
  16. package/dist/commands/formula.js +3 -3
  17. package/dist/commands/formula.js.map +2 -2
  18. package/dist/commands/list.js +5 -4
  19. package/dist/commands/list.js.map +2 -2
  20. package/dist/commands/login.js +6 -5
  21. package/dist/commands/login.js.map +2 -2
  22. package/dist/commands/model.js +5 -4
  23. package/dist/commands/model.js.map +2 -2
  24. package/dist/commands/push.js +5 -7
  25. package/dist/commands/push.js.map +2 -2
  26. package/dist/commands/run.js +3 -3
  27. package/dist/commands/run.js.map +2 -2
  28. package/dist/commands/sheets.js +3 -3
  29. package/dist/commands/sheets.js.map +2 -2
  30. package/dist/commands/variables.js +5 -4
  31. package/dist/commands/variables.js.map +2 -2
  32. package/dist/mcp/index.js +1 -1
  33. package/dist/mcp/index.js.map +2 -2
  34. package/dist/mcp/tools/appTools.js +30 -60
  35. package/dist/mcp/tools/appTools.js.map +2 -2
  36. package/dist/mcp/tools/cellTools.js +4 -6
  37. package/dist/mcp/tools/cellTools.js.map +2 -2
  38. package/dist/mcp/tools/dashboardTools.js +34 -56
  39. package/dist/mcp/tools/dashboardTools.js.map +2 -2
  40. package/dist/mcp/tools/dataTools.js +17 -38
  41. package/dist/mcp/tools/dataTools.js.map +2 -2
  42. package/dist/mcp/tools/folderTools.js +7 -11
  43. package/dist/mcp/tools/folderTools.js.map +2 -2
  44. package/dist/mcp/tools/modelTools.js +104 -159
  45. package/dist/mcp/tools/modelTools.js.map +2 -2
  46. package/dist/mcp/tools/runTools.js +5 -11
  47. package/dist/mcp/tools/runTools.js.map +2 -2
  48. package/dist/mcp/tools/sheetTools.js +31 -51
  49. package/dist/mcp/tools/sheetTools.js.map +2 -2
  50. package/dist/mcp/tools/syncTools.js +27 -57
  51. package/dist/mcp/tools/syncTools.js.map +2 -2
  52. package/dist/mcp/utils/session.js +2 -2
  53. package/dist/mcp/utils/session.js.map +2 -2
  54. package/dist/services/appSyncService.js.map +1 -1
  55. package/dist/services/apps.js +149 -0
  56. package/dist/services/apps.js.map +7 -0
  57. package/dist/services/authErrors.js +77 -0
  58. package/dist/services/authErrors.js.map +7 -0
  59. package/dist/services/configService.js +7 -4
  60. package/dist/services/configService.js.map +2 -2
  61. package/dist/services/credentials.js +87 -0
  62. package/dist/services/credentials.js.map +7 -0
  63. package/dist/services/farseerService.js +247 -112
  64. package/dist/services/farseerService.js.map +2 -2
  65. package/dist/services/httpError.js +35 -0
  66. package/dist/services/httpError.js.map +7 -0
  67. package/dist/services/modelExport.js +63 -0
  68. package/dist/services/modelExport.js.map +7 -0
  69. package/dist/services/organisation.js +88 -0
  70. package/dist/services/organisation.js.map +7 -0
  71. package/dist/services/preflight.js +10 -13
  72. package/dist/services/preflight.js.map +2 -2
  73. package/dist/services/syncService.js +2 -2
  74. package/dist/services/syncService.js.map +2 -2
  75. package/dist/utils/constants.js +2 -5
  76. package/dist/utils/constants.js.map +2 -2
  77. package/dist/utils/fileLogger.js +24 -1
  78. package/dist/utils/fileLogger.js.map +2 -2
  79. package/dist/utils/folderMatch.js +49 -0
  80. package/dist/utils/folderMatch.js.map +7 -0
  81. package/dist/utils/helpers.js +26 -0
  82. package/dist/utils/helpers.js.map +2 -2
  83. package/dist/utils/syncScope.js +44 -0
  84. package/dist/utils/syncScope.js.map +7 -0
  85. package/docs/api-reference.md +13 -1
  86. package/package.json +1 -1
  87. package/dist/services/farseerApi.js +0 -716
  88. package/dist/services/farseerApi.js.map +0 -7
  89. package/dist/services/farseerFactory.js +0 -288
  90. package/dist/services/farseerFactory.js.map +0 -7
@@ -29,91 +29,157 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
29
29
  var farseerService_exports = {};
30
30
  __export(farseerService_exports, {
31
31
  FarseerService: () => FarseerService,
32
+ basePathOf: () => basePathOf,
33
+ getFreshAccessToken: () => getFreshAccessToken,
32
34
  loginWithBrowser: () => loginWithBrowser,
33
35
  refreshAccessToken: () => refreshAccessToken,
34
36
  resolveRealm: () => resolveRealm
35
37
  });
36
38
  module.exports = __toCommonJS(farseerService_exports);
37
39
  var farseer = __toESM(require("farseer-client"));
40
+ var import_apiVersion = require("farseer-client/dist/generated/apiVersion");
38
41
  var import_configService = require("./configService");
39
- var import_farseerApi = require("./farseerApi");
42
+ var import_apps = require("./apps");
43
+ var import_modelExport = require("./modelExport");
40
44
  var import_errorFormatter = require("../utils/errorFormatter");
45
+ var import_folderMatch = require("../utils/folderMatch");
46
+ var import_httpError = require("./httpError");
47
+ var import_authErrors = require("./authErrors");
41
48
  var import_logger = require("../utils/logger");
49
+ function basePathOf(auth) {
50
+ return auth.kind === "jwt" ? auth.basePath : auth.credential.basePath;
51
+ }
52
+ function authHeaders(auth) {
53
+ return auth.kind === "jwt" ? { "X-TENANT-ID": auth.tenant, Authorization: `Bearer ${auth.accessToken}` } : { "X-TENANT-ID": auth.credential.tenantId, "X-API-KEY": auth.credential.apiKey };
54
+ }
55
+ function failureReason(error) {
56
+ if (!(error instanceof import_httpError.HttpError)) {
57
+ return "unreachable";
58
+ }
59
+ if (error.status === 403 && (0, import_authErrors.mentionsUnknownTenant)(error.message)) {
60
+ return "tenant-unknown";
61
+ }
62
+ if (error.status === 401 || error.status === 403) {
63
+ return "rejected";
64
+ }
65
+ return "server-error";
66
+ }
67
+ function freshTokenMiddleware() {
68
+ return {
69
+ async pre({ url, init }) {
70
+ const accessToken = await getFreshAccessToken();
71
+ if (!accessToken) {
72
+ return { url, init };
73
+ }
74
+ return {
75
+ url,
76
+ init: { ...init, headers: { ...init.headers, Authorization: `Bearer ${accessToken}` } }
77
+ };
78
+ }
79
+ };
80
+ }
42
81
  class FarseerService {
43
- constructor(credential) {
44
- this.credential = credential;
82
+ constructor(auth) {
83
+ this.auth = auth;
45
84
  this.client = new farseer.FarseerClient({
46
- basePath: credential.basePath,
47
- headers: {
48
- "X-TENANT-ID": credential.tenantId,
49
- "X-API-KEY": credential.apiKey
50
- }
85
+ basePath: basePathOf(auth),
86
+ headers: authHeaders(auth),
87
+ middleware: auth.kind === "jwt" ? [freshTokenMiddleware()] : []
51
88
  });
52
89
  }
53
- static fromUserAuth(tenant, basePath) {
54
- const auth = (0, import_configService.getUserAuth)();
55
- if (!auth) return null;
56
- const service = new FarseerService({
57
- type: "apiKey",
58
- tenantId: tenant,
59
- apiKey: "",
60
- basePath
61
- });
62
- service.client = new farseer.FarseerClient({
63
- basePath,
64
- headers: {
65
- "X-TENANT-ID": tenant
66
- },
67
- accessToken: auth.accessToken
68
- });
69
- return service;
90
+ /**
91
+ * The SDK client underneath, for the read/query surface that wants it raw.
92
+ *
93
+ * The same instance this class uses, deliberately: a second one would derive
94
+ * the host and headers a second time, and the SDK caches its tag map per
95
+ * instance, so two of them pay for it twice.
96
+ */
97
+ get native() {
98
+ return this.client;
70
99
  }
71
- async testConnection() {
100
+ /**
101
+ * Is this credential good? Asked of `/organization`, which answers it
102
+ * directly — 401 for a credential the server rejects, 200 otherwise, the
103
+ * same for both kinds. Nothing about the tenant's folders can make a valid
104
+ * credential look invalid.
105
+ *
106
+ * The ways it can fail are not interchangeable: "log in again" is useless
107
+ * advice for a dropped connection, and "your key was rejected" is worse than
108
+ * useless for a key that works at an organisation without this tenant.
109
+ */
110
+ async checkConnection() {
72
111
  try {
73
- await this.client.getItemByPath(["Files"]);
74
- return true;
75
- } catch {
76
- return false;
112
+ await this.getOrganizationInfo();
113
+ return { ok: true };
114
+ } catch (error) {
115
+ return {
116
+ ok: false,
117
+ reason: failureReason(error),
118
+ message: error instanceof Error ? error.message : String(error)
119
+ };
77
120
  }
78
121
  }
79
122
  async getOrganizationInfo() {
80
123
  return this.apiRequest("/organization", "GET");
81
124
  }
82
125
  async getFilesFolder() {
83
- try {
84
- const item = await this.client.getItemByPath(["Files"]);
85
- return {
86
- id: item.id,
87
- name: item.name,
88
- type: item.type
89
- };
90
- } catch {
91
- return null;
92
- }
126
+ return this.findFolder(["Files"]);
93
127
  }
128
+ /**
129
+ * The folder at `folderPath`, for callers that need its id. Exposed because
130
+ * the SDK's own getItemByPath is not a path lookup — see findFolder.
131
+ */
132
+ async getFolderByPath(folderPath) {
133
+ return this.findFolder(folderPath);
134
+ }
135
+ /**
136
+ * Every failure throws. An empty list is a claim rather than a shrug:
137
+ * SyncService.checkRemoteChanges derives what was deleted on the server by
138
+ * subtracting this listing from sync state, so `[]` says the tenant was
139
+ * emptied and a mirroring pull acts on it.
140
+ */
94
141
  async listFiles(folderPath = ["Files"]) {
95
- const files = [];
142
+ const folder = await this.requireFolderForListing(folderPath);
143
+ return this.listFilesUnder(folder.id, folderPath);
144
+ }
145
+ /**
146
+ * Resolving the root of the walk is the only part that needs a path. Every
147
+ * level below it recurses on the id already present in its parent's
148
+ * listing — walking the path again per subfolder turned a four-deep tree
149
+ * into fourteen requests where five do.
150
+ */
151
+ async listFilesUnder(folderId, folderPath) {
152
+ let items;
96
153
  try {
97
- const folder = await this.client.getItemByPath(folderPath);
98
- const folderContent = await this.client.folders.listItemsBatch([{ id: folder.id }]);
99
- for (const item of folderContent[0]?.items || []) {
100
- const itemPath = [...folderPath.slice(1), item.name].join("/");
101
- if (item.type === farseer.FolderItemType.Folder) {
102
- const subFiles = await this.listFiles([...folderPath, item.name]);
103
- files.push(...subFiles);
104
- } else if (item.type === farseer.FolderItemType.FarseerFile && "reference" in item) {
105
- files.push({
106
- name: item.name,
107
- path: itemPath,
108
- reference: item.reference
109
- });
110
- }
111
- }
154
+ const folderContent = await this.client.folders.listItemsBatch([{ id: folderId }]);
155
+ items = folderContent[0]?.items ?? [];
112
156
  } catch (error) {
113
- return [];
157
+ throw await (0, import_errorFormatter.toError)(error, `Failed to list files in ${folderPath.join("/") || "root"}`);
158
+ }
159
+ const files = [];
160
+ for (const item of items) {
161
+ const itemPath = [...folderPath.slice(1), item.name].join("/");
162
+ if (item.type === farseer.FolderItemType.Folder) {
163
+ const subFiles = await this.listFilesUnder(item.id, [...folderPath, item.name]);
164
+ files.push(...subFiles);
165
+ } else if (item.type === farseer.FolderItemType.FarseerFile && "reference" in item) {
166
+ files.push({
167
+ name: item.name,
168
+ path: itemPath,
169
+ reference: item.reference
170
+ });
171
+ }
114
172
  }
115
173
  return files;
116
174
  }
175
+ /** The listing root, with the path kept in the message on failure. */
176
+ async requireFolderForListing(folderPath) {
177
+ try {
178
+ return await this.requireFolder(folderPath);
179
+ } catch (error) {
180
+ throw await (0, import_errorFormatter.toError)(error, `Failed to list files in ${folderPath.join("/") || "root"}`);
181
+ }
182
+ }
117
183
  async getFileContent(reference) {
118
184
  const blob = await this.client.farseerFiles.get(reference);
119
185
  return await blob.text();
@@ -135,7 +201,7 @@ class FarseerService {
135
201
  }
136
202
  async createFile(content, fileName, folderPath = ["Files"]) {
137
203
  await this.ensureFolderPath(folderPath);
138
- const folder = await this.client.getItemByPath(folderPath);
204
+ const folder = await this.requireFolder(folderPath);
139
205
  const file = this.toUploadFile(content, fileName);
140
206
  try {
141
207
  await this.client.farseerFiles.create(file, "GENERAL", folder.id.toString());
@@ -162,12 +228,9 @@ class FarseerService {
162
228
  const currentPath = [];
163
229
  for (const segment of folderPath) {
164
230
  currentPath.push(segment);
165
- try {
166
- await this.client.getItemByPath(currentPath);
167
- } catch {
231
+ if (!await this.findFolder(currentPath)) {
168
232
  if (currentPath.length > 1) {
169
- const parentPath = currentPath.slice(0, -1);
170
- const parent = await this.client.getItemByPath(parentPath);
233
+ const parent = await this.requireFolder(currentPath.slice(0, -1));
171
234
  await this.client.folders.create({
172
235
  parentId: parent.id,
173
236
  name: segment,
@@ -177,26 +240,61 @@ class FarseerService {
177
240
  }
178
241
  }
179
242
  }
243
+ /**
244
+ * The file at `filePath`, or null when there isn't one.
245
+ *
246
+ * Absence is a legitimate answer here — the path is user-supplied — but a
247
+ * failed request is not: the one consumer is SyncService.getFileDiff, which
248
+ * would read it as the file having no remote content. `findFolder` keeps the
249
+ * two apart.
250
+ */
180
251
  async getFileByPath(filePath) {
181
252
  const pathParts = ["Files", ...filePath.split("/")];
182
253
  const fileName = pathParts.pop();
183
- const folderPath = pathParts;
184
- try {
185
- const folder = await this.client.getItemByPath(folderPath);
186
- const folderContent = await this.client.folders.listItemsBatch([{ id: folder.id }]);
187
- for (const item of folderContent[0]?.items || []) {
188
- if (item.name === fileName && item.type === farseer.FolderItemType.FarseerFile && "reference" in item) {
189
- return {
190
- name: item.name,
191
- path: filePath,
192
- reference: item.reference
193
- };
194
- }
195
- }
196
- } catch {
254
+ const folder = await this.findFolder(pathParts);
255
+ if (!folder) {
197
256
  return null;
198
257
  }
199
- return null;
258
+ const folderContent = await this.client.folders.listItemsBatch([{ id: folder.id }]);
259
+ const match = (folderContent[0]?.items ?? []).find(
260
+ (item) => item.name === fileName && item.type === farseer.FolderItemType.FarseerFile && "reference" in item
261
+ );
262
+ return match ? { name: match.name, path: filePath, reference: match.reference } : null;
263
+ }
264
+ /**
265
+ * The folder at `folderPath`, or null when a segment of it isn't there. Only
266
+ * absence returns null; a failed listing throws.
267
+ *
268
+ * Not the SDK's `getItemByPath`: for a single-segment path it ignores the
269
+ * path entirely and name-searches the whole tenant across folders,
270
+ * dashboards, sheets, dimension tables and variables, capped at 20 results.
271
+ * The match itself is exact, so a near-miss name is harmless — but a second
272
+ * item named exactly `Files` anywhere in the tenant makes it refuse, and 20
273
+ * prefix matches crowd the real folder off the only page it looks at. A path
274
+ * is a path, so each segment is matched inside its parent's listing.
275
+ */
276
+ async findFolder(folderPath) {
277
+ let parentId = null;
278
+ let found = null;
279
+ for (const segment of folderPath) {
280
+ const contents = await this.client.folders.listItemsBatch([{ id: parentId }]);
281
+ const folders = (contents[0]?.items ?? []).filter((item) => item.type === farseer.FolderItemType.Folder);
282
+ const match = (0, import_folderMatch.matchFolderSegment)(folders, segment);
283
+ if (!match) {
284
+ return null;
285
+ }
286
+ found = { id: match.id, name: match.name, type: match.type };
287
+ parentId = match.id;
288
+ }
289
+ return found;
290
+ }
291
+ /** Same walk, for callers that can only proceed if the folder is there. */
292
+ async requireFolder(folderPath) {
293
+ const folder = await this.findFolder(folderPath);
294
+ if (!folder) {
295
+ throw new Error(`Folder not found: ${folderPath.join("/")}`);
296
+ }
297
+ return folder;
200
298
  }
201
299
  async getFileMetadata(reference) {
202
300
  try {
@@ -220,15 +318,6 @@ class FarseerService {
220
318
  const arrayBuffer = await blob.arrayBuffer();
221
319
  return Buffer.from(arrayBuffer);
222
320
  }
223
- isTextFile(filename) {
224
- const ext = filename.toLowerCase().split(".").pop() || "";
225
- return ["ts", "js", "mjs", "cjs", "json", "txt", "md", "csv", "xml", "html", "css", "yaml", "yml"].includes(
226
- ext
227
- );
228
- }
229
- isBinaryFile(filename) {
230
- return !this.isTextFile(filename);
231
- }
232
321
  // ==================== Apps (Remote Jobs) API ====================
233
322
  /**
234
323
  * List all apps (Remote Jobs) on the tenant
@@ -237,7 +326,7 @@ class FarseerService {
237
326
  const response = await this.client.remoteJobs.list();
238
327
  return response.map((app) => ({
239
328
  name: app.name,
240
- type: import_farseerApi.REMOTE_JOB_ITEM_TYPE,
329
+ type: import_apps.REMOTE_JOB_ITEM_TYPE,
241
330
  reference: String(app.id)
242
331
  }));
243
332
  }
@@ -251,8 +340,11 @@ class FarseerService {
251
340
  app.scriptFiles = await this.resolveAppScripts(app.sourceFolderId);
252
341
  }
253
342
  return app;
254
- } catch {
255
- return null;
343
+ } catch (error) {
344
+ if (error instanceof import_httpError.HttpError && error.status === 404) {
345
+ return null;
346
+ }
347
+ throw await (0, import_errorFormatter.toError)(error, `Failed to load app ${referenceId}`);
256
348
  }
257
349
  }
258
350
  /**
@@ -262,13 +354,25 @@ class FarseerService {
262
354
  try {
263
355
  const folderContent = await this.client.folders.listItemsBatch([{ id: sourceFolderId }]);
264
356
  return (folderContent[0]?.items || []).filter((item) => item.type === farseer.FolderItemType.FarseerFile && "reference" in item).map((item) => ({ id: item.reference, name: item.name }));
265
- } catch {
266
- return [];
357
+ } catch (error) {
358
+ const status = error?.status;
359
+ if (status === 404) {
360
+ return [];
361
+ }
362
+ throw error;
267
363
  }
268
364
  }
365
+ /**
366
+ * Null means the folder is not there. A failed request throws, so a caller
367
+ * reporting "no such folder" cannot say it about a 500 or a dropped
368
+ * connection.
369
+ */
269
370
  async resolveSourceFolder(relativePath) {
270
371
  const segments = relativePath.split("/").map((s) => s.trim()).filter(Boolean);
271
- const folder = await this.client.getItemByPath(["Files", ...segments]);
372
+ const folder = await this.findFolder(["Files", ...segments]);
373
+ if (!folder) {
374
+ return null;
375
+ }
272
376
  const scripts = await this.resolveAppScripts(folder.id);
273
377
  return { id: folder.id, scripts };
274
378
  }
@@ -300,7 +404,7 @@ class FarseerService {
300
404
  * Update an app
301
405
  */
302
406
  async updateApp(referenceId, update, currentApp) {
303
- await this.apiRequest(`/remoteJobs/${referenceId}`, "PUT", (0, import_farseerApi.mergeAppUpdate)(currentApp, update));
407
+ await this.apiRequest(`/remoteJobs/${referenceId}`, "PUT", (0, import_apps.mergeAppUpdate)(currentApp, update));
304
408
  const app = await this.getApp(referenceId);
305
409
  if (!app) {
306
410
  throw new Error(`Failed to fetch updated app ${referenceId}`);
@@ -314,7 +418,7 @@ class FarseerService {
314
418
  return [];
315
419
  }
316
420
  try {
317
- return await this.client.folders.resolveItems((0, import_farseerApi.remoteJobReverseReferences)(remoteJobIds));
421
+ return await this.client.folders.resolveItems((0, import_apps.remoteJobReverseReferences)(remoteJobIds));
318
422
  } catch (error) {
319
423
  throw await (0, import_errorFormatter.toError)(error, `Failed to resolve folder items for Remote Job(s): ${remoteJobIds.join(", ")}`);
320
424
  }
@@ -323,7 +427,7 @@ class FarseerService {
323
427
  // caller can hand this a raw node id. See `resolveAppItemNodeId`.
324
428
  async deleteApp(remoteJobId) {
325
429
  const items = await this.resolveRemoteJobItems([remoteJobId]);
326
- const itemNodeId = (0, import_farseerApi.resolveAppItemNodeId)(remoteJobId, items);
430
+ const itemNodeId = (0, import_apps.resolveAppItemNodeId)(remoteJobId, items);
327
431
  try {
328
432
  await this.client.folders.deleteItemsBatch([{ id: itemNodeId }]);
329
433
  } catch (error) {
@@ -338,7 +442,7 @@ class FarseerService {
338
442
  return allFiles.filter((f) => f.name.endsWith(".ts") || f.name.endsWith(".js")).map((f) => ({
339
443
  id: f.reference,
340
444
  name: f.path
341
- // Use full path to support scripts in subfolders (matches FarseerApi)
445
+ // Full path, not the file name: scripts live in subfolders.
342
446
  }));
343
447
  }
344
448
  /**
@@ -385,9 +489,12 @@ class FarseerService {
385
489
  gid: v.gid,
386
490
  name: v.name,
387
491
  description: v.description,
492
+ // `model export --json` is documented as the raw export, and the
493
+ // browser-login client used to hand it back unmapped.
494
+ notes: v.notes,
388
495
  formula: v.formula,
389
496
  tables: v.tables,
390
- members: v.members?.flat() ?? [],
497
+ members: v.members ?? [],
391
498
  rollupType: v.rollupType,
392
499
  dataType: v.dataType,
393
500
  numberFormat: v.numberFormat,
@@ -405,11 +512,11 @@ class FarseerService {
405
512
  };
406
513
  }
407
514
  /**
408
- * See `loadDimensionTableViaEntitiesApi`. Same logic as the JWT
409
- * path, just on the apiKey-auth client.
515
+ * Scoped through the entities API rather than `exportModel({ tableGids })`,
516
+ * which 500s for some tables on large tenants.
410
517
  */
411
518
  async loadDimensionTableWithMembers(name) {
412
- return (0, import_farseerApi.loadDimensionTableViaEntitiesApi)(this.client, name);
519
+ return (0, import_modelExport.loadDimensionTableViaEntitiesApi)(this.client, name);
413
520
  }
414
521
  async buildModelFromTagMaps(options = {}) {
415
522
  const types = options.types ?? ["DTAB", "VAR"];
@@ -470,23 +577,21 @@ class FarseerService {
470
577
  * Get the Apps folder ID
471
578
  */
472
579
  async getAppsFolderId() {
473
- try {
474
- const item = await this.client.getItemByPath(["Apps"]);
475
- return item.id;
476
- } catch {
477
- return null;
478
- }
580
+ return (await this.findFolder(["Apps"]))?.id ?? null;
479
581
  }
480
582
  /**
481
583
  * Make a direct API request (for endpoints not in farseer-client)
482
584
  */
483
585
  async apiRequest(endpoint, method, body) {
484
- const url = `${this.credential.basePath}${endpoint}`;
586
+ const url = `${basePathOf(this.auth)}${endpoint}`;
587
+ const auth = this.auth.kind === "jwt" ? { ...this.auth, accessToken: await getFreshAccessToken() ?? this.auth.accessToken } : this.auth;
485
588
  const headers = {
486
589
  "Content-Type": "application/json",
487
- "X-TENANT-ID": this.credential.tenantId,
488
- "X-API-KEY": this.credential.apiKey,
489
- "x-api-version": "3.3.0"
590
+ // The SDK stamps this from its own generated constant, and these
591
+ // requests have to agree with it. Deep path because the package root
592
+ // re-exports the models but not API_VERSION.
593
+ "x-api-version": import_apiVersion.API_VERSION,
594
+ ...authHeaders(auth)
490
595
  };
491
596
  const response = await fetch(url, {
492
597
  method,
@@ -494,7 +599,7 @@ class FarseerService {
494
599
  body: body ? JSON.stringify(body) : void 0
495
600
  });
496
601
  if (!response.ok) {
497
- throw new Error(`HTTP ${response.status}: ${await response.text()}`);
602
+ throw new import_httpError.HttpError(response.status, `HTTP ${response.status}: ${await response.text()}`);
498
603
  }
499
604
  if (response.status === 204) {
500
605
  return void 0;
@@ -759,6 +864,34 @@ ${url}
759
864
  );
760
865
  });
761
866
  }
867
+ let refreshInFlight = null;
868
+ function getFreshAccessToken() {
869
+ return refreshInFlight ??= mintAccessToken().finally(() => {
870
+ refreshInFlight = null;
871
+ });
872
+ }
873
+ async function mintAccessToken() {
874
+ const auth = (0, import_configService.getUserAuth)();
875
+ if (!auth) {
876
+ return null;
877
+ }
878
+ if ((0, import_configService.isUserAuthValid)(auth)) {
879
+ return auth.accessToken;
880
+ }
881
+ import_logger.logger.dim("Token expired, refreshing...");
882
+ const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || "master");
883
+ if (!refreshed) {
884
+ return null;
885
+ }
886
+ (0, import_configService.setUserAuth)({
887
+ accessToken: refreshed.accessToken,
888
+ refreshToken: refreshed.refreshToken,
889
+ expiresAt: new Date(Date.now() + refreshed.expiresIn * 1e3).toISOString(),
890
+ realm: auth.realm
891
+ });
892
+ import_logger.logger.dim("Token refreshed");
893
+ return refreshed.accessToken;
894
+ }
762
895
  async function refreshAccessToken(refreshToken, realm = "master") {
763
896
  const tokenUrl = `https://login.farseer.io/auth/realms/${realm}/protocol/openid-connect/token`;
764
897
  try {
@@ -789,6 +922,8 @@ async function refreshAccessToken(refreshToken, realm = "master") {
789
922
  // Annotate the CommonJS export names for ESM import in node:
790
923
  0 && (module.exports = {
791
924
  FarseerService,
925
+ basePathOf,
926
+ getFreshAccessToken,
792
927
  loginWithBrowser,
793
928
  refreshAccessToken,
794
929
  resolveRealm