farseer-cli 1.10.3 → 1.11.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 (84) hide show
  1. package/README.md +5 -0
  2. package/dist/commands/app.js +41 -42
  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 +13 -15
  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 +38 -23
  35. package/dist/mcp/tools/appTools.js.map +2 -2
  36. package/dist/mcp/tools/dataTools.js +5 -2
  37. package/dist/mcp/tools/dataTools.js.map +2 -2
  38. package/dist/mcp/tools/modelTools.js +45 -48
  39. package/dist/mcp/tools/modelTools.js.map +2 -2
  40. package/dist/mcp/tools/runTools.js +12 -7
  41. package/dist/mcp/tools/runTools.js.map +2 -2
  42. package/dist/mcp/utils/helpers.js +41 -0
  43. package/dist/mcp/utils/helpers.js.map +2 -2
  44. package/dist/mcp/utils/session.js +2 -2
  45. package/dist/mcp/utils/session.js.map +2 -2
  46. package/dist/services/appSyncService.js.map +1 -1
  47. package/dist/services/apps.js +149 -0
  48. package/dist/services/apps.js.map +7 -0
  49. package/dist/services/authErrors.js +77 -0
  50. package/dist/services/authErrors.js.map +7 -0
  51. package/dist/services/configService.js +7 -4
  52. package/dist/services/configService.js.map +2 -2
  53. package/dist/services/credentials.js +87 -0
  54. package/dist/services/credentials.js.map +7 -0
  55. package/dist/services/farseerService.js +247 -123
  56. package/dist/services/farseerService.js.map +2 -2
  57. package/dist/services/httpError.js +35 -0
  58. package/dist/services/httpError.js.map +7 -0
  59. package/dist/services/modelExport.js +63 -0
  60. package/dist/services/modelExport.js.map +7 -0
  61. package/dist/services/organisation.js +88 -0
  62. package/dist/services/organisation.js.map +7 -0
  63. package/dist/services/preflight.js +10 -13
  64. package/dist/services/preflight.js.map +2 -2
  65. package/dist/services/syncService.js +2 -2
  66. package/dist/services/syncService.js.map +2 -2
  67. package/dist/utils/appResolver.js +63 -0
  68. package/dist/utils/appResolver.js.map +7 -0
  69. package/dist/utils/constants.js +2 -5
  70. package/dist/utils/constants.js.map +2 -2
  71. package/dist/utils/fileLogger.js +24 -1
  72. package/dist/utils/fileLogger.js.map +2 -2
  73. package/dist/utils/folderMatch.js +49 -0
  74. package/dist/utils/folderMatch.js.map +7 -0
  75. package/dist/utils/helpers.js +98 -1
  76. package/dist/utils/helpers.js.map +3 -3
  77. package/dist/utils/syncScope.js +44 -0
  78. package/dist/utils/syncScope.js.map +7 -0
  79. package/docs/api-reference.md +13 -1
  80. package/package.json +1 -1
  81. package/dist/services/farseerApi.js +0 -716
  82. package/dist/services/farseerApi.js.map +0 -7
  83. package/dist/services/farseerFactory.js +0 -276
  84. 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"]);
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);
93
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,26 +354,27 @@ 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
  }
269
- async resolveSourceFolder(relativePath) {
270
- const segments = relativePath.split("/").map((s) => s.trim()).filter(Boolean);
271
- const folder = await this.client.getItemByPath(["Files", ...segments]);
272
- const scripts = await this.resolveAppScripts(folder.id);
273
- return { id: folder.id, scripts };
274
- }
275
365
  /**
276
- * Get app by name
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.
277
369
  */
278
- async getAppByName(name) {
279
- const apps = await this.listApps();
280
- const app = apps.find((a) => a.name.toLowerCase() === name.toLowerCase());
281
- if (!app) {
370
+ async resolveSourceFolder(relativePath) {
371
+ const segments = relativePath.split("/").map((s) => s.trim()).filter(Boolean);
372
+ const folder = await this.findFolder(["Files", ...segments]);
373
+ if (!folder) {
282
374
  return null;
283
375
  }
284
- return this.getApp(app.reference);
376
+ const scripts = await this.resolveAppScripts(folder.id);
377
+ return { id: folder.id, scripts };
285
378
  }
286
379
  /**
287
380
  * Create a new app
@@ -300,7 +393,7 @@ class FarseerService {
300
393
  * Update an app
301
394
  */
302
395
  async updateApp(referenceId, update, currentApp) {
303
- await this.apiRequest(`/remoteJobs/${referenceId}`, "PUT", (0, import_farseerApi.mergeAppUpdate)(currentApp, update));
396
+ await this.apiRequest(`/remoteJobs/${referenceId}`, "PUT", (0, import_apps.mergeAppUpdate)(currentApp, update));
304
397
  const app = await this.getApp(referenceId);
305
398
  if (!app) {
306
399
  throw new Error(`Failed to fetch updated app ${referenceId}`);
@@ -314,7 +407,7 @@ class FarseerService {
314
407
  return [];
315
408
  }
316
409
  try {
317
- return await this.client.folders.resolveItems((0, import_farseerApi.remoteJobReverseReferences)(remoteJobIds));
410
+ return await this.client.folders.resolveItems((0, import_apps.remoteJobReverseReferences)(remoteJobIds));
318
411
  } catch (error) {
319
412
  throw await (0, import_errorFormatter.toError)(error, `Failed to resolve folder items for Remote Job(s): ${remoteJobIds.join(", ")}`);
320
413
  }
@@ -323,7 +416,7 @@ class FarseerService {
323
416
  // caller can hand this a raw node id. See `resolveAppItemNodeId`.
324
417
  async deleteApp(remoteJobId) {
325
418
  const items = await this.resolveRemoteJobItems([remoteJobId]);
326
- const itemNodeId = (0, import_farseerApi.resolveAppItemNodeId)(remoteJobId, items);
419
+ const itemNodeId = (0, import_apps.resolveAppItemNodeId)(remoteJobId, items);
327
420
  try {
328
421
  await this.client.folders.deleteItemsBatch([{ id: itemNodeId }]);
329
422
  } catch (error) {
@@ -338,7 +431,7 @@ class FarseerService {
338
431
  return allFiles.filter((f) => f.name.endsWith(".ts") || f.name.endsWith(".js")).map((f) => ({
339
432
  id: f.reference,
340
433
  name: f.path
341
- // Use full path to support scripts in subfolders (matches FarseerApi)
434
+ // Full path, not the file name: scripts live in subfolders.
342
435
  }));
343
436
  }
344
437
  /**
@@ -385,9 +478,12 @@ class FarseerService {
385
478
  gid: v.gid,
386
479
  name: v.name,
387
480
  description: v.description,
481
+ // `model export --json` is documented as the raw export, and the
482
+ // browser-login client used to hand it back unmapped.
483
+ notes: v.notes,
388
484
  formula: v.formula,
389
485
  tables: v.tables,
390
- members: v.members?.flat() ?? [],
486
+ members: v.members ?? [],
391
487
  rollupType: v.rollupType,
392
488
  dataType: v.dataType,
393
489
  numberFormat: v.numberFormat,
@@ -405,11 +501,11 @@ class FarseerService {
405
501
  };
406
502
  }
407
503
  /**
408
- * See `loadDimensionTableViaEntitiesApi`. Same logic as the JWT
409
- * path, just on the apiKey-auth client.
504
+ * Scoped through the entities API rather than `exportModel({ tableGids })`,
505
+ * which 500s for some tables on large tenants.
410
506
  */
411
507
  async loadDimensionTableWithMembers(name) {
412
- return (0, import_farseerApi.loadDimensionTableViaEntitiesApi)(this.client, name);
508
+ return (0, import_modelExport.loadDimensionTableViaEntitiesApi)(this.client, name);
413
509
  }
414
510
  async buildModelFromTagMaps(options = {}) {
415
511
  const types = options.types ?? ["DTAB", "VAR"];
@@ -470,23 +566,21 @@ class FarseerService {
470
566
  * Get the Apps folder ID
471
567
  */
472
568
  async getAppsFolderId() {
473
- try {
474
- const item = await this.client.getItemByPath(["Apps"]);
475
- return item.id;
476
- } catch {
477
- return null;
478
- }
569
+ return (await this.findFolder(["Apps"]))?.id ?? null;
479
570
  }
480
571
  /**
481
572
  * Make a direct API request (for endpoints not in farseer-client)
482
573
  */
483
574
  async apiRequest(endpoint, method, body) {
484
- const url = `${this.credential.basePath}${endpoint}`;
575
+ const url = `${basePathOf(this.auth)}${endpoint}`;
576
+ const auth = this.auth.kind === "jwt" ? { ...this.auth, accessToken: await getFreshAccessToken() ?? this.auth.accessToken } : this.auth;
485
577
  const headers = {
486
578
  "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"
579
+ // The SDK stamps this from its own generated constant, and these
580
+ // requests have to agree with it. Deep path because the package root
581
+ // re-exports the models but not API_VERSION.
582
+ "x-api-version": import_apiVersion.API_VERSION,
583
+ ...authHeaders(auth)
490
584
  };
491
585
  const response = await fetch(url, {
492
586
  method,
@@ -494,7 +588,7 @@ class FarseerService {
494
588
  body: body ? JSON.stringify(body) : void 0
495
589
  });
496
590
  if (!response.ok) {
497
- throw new Error(`HTTP ${response.status}: ${await response.text()}`);
591
+ throw new import_httpError.HttpError(response.status, `HTTP ${response.status}: ${await response.text()}`);
498
592
  }
499
593
  if (response.status === 204) {
500
594
  return void 0;
@@ -759,6 +853,34 @@ ${url}
759
853
  );
760
854
  });
761
855
  }
856
+ let refreshInFlight = null;
857
+ function getFreshAccessToken() {
858
+ return refreshInFlight ??= mintAccessToken().finally(() => {
859
+ refreshInFlight = null;
860
+ });
861
+ }
862
+ async function mintAccessToken() {
863
+ const auth = (0, import_configService.getUserAuth)();
864
+ if (!auth) {
865
+ return null;
866
+ }
867
+ if ((0, import_configService.isUserAuthValid)(auth)) {
868
+ return auth.accessToken;
869
+ }
870
+ import_logger.logger.dim("Token expired, refreshing...");
871
+ const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || "master");
872
+ if (!refreshed) {
873
+ return null;
874
+ }
875
+ (0, import_configService.setUserAuth)({
876
+ accessToken: refreshed.accessToken,
877
+ refreshToken: refreshed.refreshToken,
878
+ expiresAt: new Date(Date.now() + refreshed.expiresIn * 1e3).toISOString(),
879
+ realm: auth.realm
880
+ });
881
+ import_logger.logger.dim("Token refreshed");
882
+ return refreshed.accessToken;
883
+ }
762
884
  async function refreshAccessToken(refreshToken, realm = "master") {
763
885
  const tokenUrl = `https://login.farseer.io/auth/realms/${realm}/protocol/openid-connect/token`;
764
886
  try {
@@ -789,6 +911,8 @@ async function refreshAccessToken(refreshToken, realm = "master") {
789
911
  // Annotate the CommonJS export names for ESM import in node:
790
912
  0 && (module.exports = {
791
913
  FarseerService,
914
+ basePathOf,
915
+ getFreshAccessToken,
792
916
  loginWithBrowser,
793
917
  refreshAccessToken,
794
918
  resolveRealm