@superblocksteam/sdk 1.5.0 → 1.5.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.
package/dist/client.js CHANGED
@@ -18,7 +18,6 @@ const SUPERBLOCKS_MAX_FILE_SIZE_MB = 10;
18
18
  const CLI_VERSION_HEADER = "x-superblocks-cli-version";
19
19
  const SUPERBLOCKS_URL_HEADER = "x-superblocks-url";
20
20
  async function fetchApplication({ cliVersion, applicationId, branch, token, superblocksBaseUrl, viewMode, injectedHeaders = {}, }) {
21
- var _a, _b;
22
21
  const serverURL = branch
23
22
  ? new URL(`${BASE_SERVER_PUBLIC_API_URL}/applications/${applicationId}/branches/${encodeURIComponent(branch)}?viewMode=${viewMode}`, superblocksBaseUrl)
24
23
  : new URL(`${BASE_SERVER_PUBLIC_API_URL}/applications/${applicationId}?viewMode=${viewMode}`, superblocksBaseUrl);
@@ -36,16 +35,15 @@ async function fetchApplication({ cliVersion, applicationId, branch, token, supe
36
35
  serverResponse = await (0, axios_1.default)(config);
37
36
  }
38
37
  catch (e) {
39
- if (axios_1.default.isAxiosError(e) && ((_a = e.response) === null || _a === void 0 ? void 0 : _a.status) === 404) {
38
+ if (axios_1.default.isAxiosError(e) && e.response?.status === 404) {
40
39
  throw new util_1.NotFoundError(`Application ${applicationId} was not found`);
41
40
  }
42
41
  throw new Error("Could not fetch application");
43
42
  }
44
- return (_b = serverResponse === null || serverResponse === void 0 ? void 0 : serverResponse.data) === null || _b === void 0 ? void 0 : _b.data;
43
+ return serverResponse?.data?.data;
45
44
  }
46
45
  exports.fetchApplication = fetchApplication;
47
46
  async function fetchApplicationBranches({ cliVersion, applicationId, token, superblocksBaseUrl, injectedHeaders = {}, }) {
48
- var _a, _b;
49
47
  const serverURL = new URL(`public/applications/${applicationId}/branches`, superblocksBaseUrl);
50
48
  let serverResponse;
51
49
  try {
@@ -61,16 +59,15 @@ async function fetchApplicationBranches({ cliVersion, applicationId, token, supe
61
59
  serverResponse = await (0, axios_1.default)(config);
62
60
  }
63
61
  catch (e) {
64
- if (axios_1.default.isAxiosError(e) && ((_a = e.response) === null || _a === void 0 ? void 0 : _a.status) === 404) {
62
+ if (axios_1.default.isAxiosError(e) && e.response?.status === 404) {
65
63
  throw new util_1.NotFoundError(`Application ${applicationId} was not found`);
66
64
  }
67
65
  throw new Error(`Could not fetch application branches: ${e.message}`);
68
66
  }
69
- return (_b = serverResponse === null || serverResponse === void 0 ? void 0 : serverResponse.data) === null || _b === void 0 ? void 0 : _b.data;
67
+ return serverResponse?.data?.data;
70
68
  }
71
69
  exports.fetchApplicationBranches = fetchApplicationBranches;
72
70
  async function fetchApplicationWithComponents({ cliVersion, applicationId, branch, token, superblocksBaseUrl, viewMode, injectedHeaders = {}, }) {
73
- var _a, _b, _c;
74
71
  const applicationWrapper = await fetchApplication({
75
72
  cliVersion,
76
73
  applicationId,
@@ -84,7 +81,7 @@ async function fetchApplicationWithComponents({ cliVersion, applicationId, branc
84
81
  return;
85
82
  }
86
83
  // if there are no custom components, just return here without trying to initialize them using bucketeer
87
- if ((0, lodash_1.isEmpty)((_b = (_a = applicationWrapper.application) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.registeredComponents)) {
84
+ if ((0, lodash_1.isEmpty)(applicationWrapper.application?.settings?.registeredComponents)) {
88
85
  return {
89
86
  ...applicationWrapper,
90
87
  componentFiles: null,
@@ -111,7 +108,7 @@ async function fetchApplicationWithComponents({ cliVersion, applicationId, branc
111
108
  return response.data;
112
109
  }
113
110
  catch (e) {
114
- if (axios_1.default.isAxiosError(e) && ((_c = e.response) === null || _c === void 0 ? void 0 : _c.status) === 404) {
111
+ if (axios_1.default.isAxiosError(e) && e.response?.status === 404) {
115
112
  throw new util_1.NotFoundError(`Application ${applicationId} was not found`);
116
113
  }
117
114
  throw new Error("Could not fetch application");
@@ -119,7 +116,6 @@ async function fetchApplicationWithComponents({ cliVersion, applicationId, branc
119
116
  }
120
117
  exports.fetchApplicationWithComponents = fetchApplicationWithComponents;
121
118
  async function fetchApplications(cliVersion, token, superblocksBaseUrl, injectedHeaders = {}) {
122
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
123
119
  try {
124
120
  const config = {
125
121
  method: "get",
@@ -137,17 +133,20 @@ async function fetchApplications(cliVersion, token, superblocksBaseUrl, injected
137
133
  let message;
138
134
  if (e instanceof axios_1.AxiosError) {
139
135
  message =
140
- (_j = (_h = (_f = (_d = (_c = (_b = (_a = e.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.responseMeta) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : JSON.stringify((_e = e.response) === null || _e === void 0 ? void 0 : _e.data)) !== null && _f !== void 0 ? _f : (_g = e.response) === null || _g === void 0 ? void 0 : _g.statusText) !== null && _h !== void 0 ? _h : e === null || e === void 0 ? void 0 : e.message) !== null && _j !== void 0 ? _j : `${e}`;
136
+ e.response?.data?.responseMeta?.message ??
137
+ JSON.stringify(e.response?.data) ??
138
+ e.response?.statusText ??
139
+ e?.message ??
140
+ `${e}`;
141
141
  }
142
142
  else {
143
- message = `${(e === null || e === void 0 ? void 0 : e.message) ? e === null || e === void 0 ? void 0 : e.message : e}`;
143
+ message = `${e?.message ? e?.message : e}`;
144
144
  }
145
145
  throw new Error(`Could not fetch applications: ${message}`);
146
146
  }
147
147
  }
148
148
  exports.fetchApplications = fetchApplications;
149
149
  async function fetchApi(cliVersion, apiId, token, superblocksBaseUrl, viewMode, branch) {
150
- var _a;
151
150
  try {
152
151
  const serverURL = branch
153
152
  ? new URL(`${BASE_SERVER_PUBLIC_API_URL}/apis/${apiId}/branches/${encodeURIComponent(branch)}?viewMode=${viewMode}`, superblocksBaseUrl)
@@ -164,7 +163,7 @@ async function fetchApi(cliVersion, apiId, token, superblocksBaseUrl, viewMode,
164
163
  return response.data.data;
165
164
  }
166
165
  catch (e) {
167
- if (axios_1.default.isAxiosError(e) && ((_a = e.response) === null || _a === void 0 ? void 0 : _a.status) === 404) {
166
+ if (axios_1.default.isAxiosError(e) && e.response?.status === 404) {
168
167
  throw new util_1.NotFoundError(`Api ${apiId} was not found`);
169
168
  }
170
169
  throw new Error("Could not fetch api");
@@ -190,7 +189,6 @@ async function fetchApis(cliVersion, token, superblocksBaseUrl) {
190
189
  }
191
190
  exports.fetchApis = fetchApis;
192
191
  async function validateGitSetup(cliVersion, resourceId, resourceType, event, localGitRepoState, token, superblocksBaseUrl, injectedHeaders) {
193
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
194
192
  let resourceName;
195
193
  try {
196
194
  const requestBody = {
@@ -229,32 +227,37 @@ async function validateGitSetup(cliVersion, resourceId, resourceType, event, loc
229
227
  throw new Error(validationResult.errors.join("\n"));
230
228
  }
231
229
  return {
232
- branchName: ((_a = validationResult.branchName) !== null && _a !== void 0 ? _a : null),
230
+ branchName: (validationResult.branchName ?? null),
233
231
  };
234
232
  }
235
233
  catch (e) {
236
234
  let message;
237
235
  if (e instanceof axios_1.AxiosError) {
238
236
  message =
239
- (_k = (_j = (_g = (_e = (_d = (_c = (_b = e.response) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.responseMeta) === null || _d === void 0 ? void 0 : _d.message) !== null && _e !== void 0 ? _e : JSON.stringify((_f = e.response) === null || _f === void 0 ? void 0 : _f.data)) !== null && _g !== void 0 ? _g : (_h = e.response) === null || _h === void 0 ? void 0 : _h.statusText) !== null && _j !== void 0 ? _j : e === null || e === void 0 ? void 0 : e.message) !== null && _k !== void 0 ? _k : `${e}`;
237
+ e.response?.data?.responseMeta?.message ??
238
+ JSON.stringify(e.response?.data) ??
239
+ e.response?.statusText ??
240
+ e?.message ??
241
+ `${e}`;
240
242
  }
241
243
  else {
242
- message = `${(e === null || e === void 0 ? void 0 : e.message) ? e === null || e === void 0 ? void 0 : e.message : e}`;
244
+ message = `${e?.message ? e?.message : e}`;
243
245
  }
244
- throw new Error(`Could not validate your git setup against Superblocks for the ${resourceType.toLowerCase()} ${resourceName !== null && resourceName !== void 0 ? resourceName : resourceId}${message ? "\n" + message : ""}`);
246
+ throw new Error(`Could not validate your git setup against Superblocks for the ${resourceType.toLowerCase()} ${resourceName ?? resourceId}${message ? "\n" + message : ""}`);
245
247
  }
246
248
  }
247
249
  exports.validateGitSetup = validateGitSetup;
248
250
  async function registerComponents(cliVersion, applicationId, componentConfigs, token, superblocksBaseUrl, branch, injectedHeaders) {
249
- var _a, _b, _c, _d, _e, _f, _g;
250
251
  try {
251
252
  const branchPath = branch ? `/branches/${encodeURIComponent(branch)}` : "";
252
253
  const userMe = await fetchCurrentUser(cliVersion, token, superblocksBaseUrl);
253
254
  const organization = userMe.organizations[0];
254
- if (organization.agentType == types_1.AgentType.ONPREMISE && (0, flag_1.signingEnabled)(userMe.flagBootstrap)) {
255
- const agentUrls = (0, utils_1.getAgentUrls)(userMe.agents, organization.agentType);
255
+ if (organization.agentType == types_1.AgentType.ONPREMISE &&
256
+ (0, flag_1.signingEnabled)(userMe.flagBootstrap)) {
257
+ const profile = process.env.SUPERBLOCKS_PROFILE;
258
+ const agentUrl = await (0, utils_1.getAgentUrl)(userMe.agents, organization.agentType, profile);
256
259
  const socket = await (0, socket_1.connectToISocketRPCServer)({
257
- agentUrls,
260
+ agentUrl,
258
261
  superblocksBaseUrl,
259
262
  token,
260
263
  });
@@ -285,7 +288,9 @@ async function registerComponents(cliVersion, applicationId, componentConfigs, t
285
288
  }
286
289
  catch (e) {
287
290
  if (e instanceof axios_1.AxiosError) {
288
- const message = (_f = (_d = (_c = (_b = (_a = e.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.responseMeta) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : JSON.stringify((_e = e.response) === null || _e === void 0 ? void 0 : _e.data)) !== null && _f !== void 0 ? _f : (_g = e.response) === null || _g === void 0 ? void 0 : _g.statusText;
291
+ const message = e.response?.data?.responseMeta?.message ??
292
+ JSON.stringify(e.response?.data) ??
293
+ e.response?.statusText;
289
294
  throw new Error(`Could not register application components ${message ? "\n" + message : ""}`);
290
295
  }
291
296
  throw new Error(`Could not register application components ${e.message ? "\n" + e.message : ""}`);
@@ -293,7 +298,6 @@ async function registerComponents(cliVersion, applicationId, componentConfigs, t
293
298
  }
294
299
  exports.registerComponents = registerComponents;
295
300
  async function uploadComponents({ cliVersion, applicationId, componentConfigs, files, token, superblocksBaseUrl, branch, }) {
296
- var _a, _b, _c, _d, _e, _f;
297
301
  superblocksBaseUrl = superblocksBaseUrl.replace(/\/$/, "");
298
302
  const bucketeerBaseUrl = (0, util_1.getBucketeerUrlFromSuperblocksUrl)(superblocksBaseUrl);
299
303
  // parse files to source and bundled files based on path
@@ -349,20 +353,21 @@ You can reduce your component bundle size by uploading static assets to a separa
349
353
  const uploadResponse = await axios_1.default.post(postURL, formData, config);
350
354
  const userMe = await fetchCurrentUser(cliVersion, token, superblocksBaseUrl);
351
355
  const organization = userMe.organizations[0];
352
- const signingRequired = organization.agentType == types_1.AgentType.ONPREMISE && (0, flag_1.signingEnabled)(userMe.flagBootstrap);
353
- let agentUrls = [];
356
+ let agentUrl;
357
+ const signingRequired = organization.agentType == types_1.AgentType.ONPREMISE &&
358
+ (0, flag_1.signingEnabled)(userMe.flagBootstrap);
354
359
  if (signingRequired) {
355
- agentUrls = (0, utils_1.getAgentUrls)(userMe.agents, organization.agentType);
360
+ agentUrl = await (0, utils_1.getAgentUrl)(userMe.agents, organization.agentType);
356
361
  }
357
362
  const socket = await (0, socket_1.connectToISocketRPCServer)({
358
- agentUrls,
363
+ agentUrl,
359
364
  superblocksBaseUrl,
360
365
  token,
361
366
  });
362
367
  try {
363
368
  await socket.call.v1.public.application.component.update({
364
369
  applicationId,
365
- branchName: branch !== null && branch !== void 0 ? branch : undefined,
370
+ branchName: branch ?? undefined,
366
371
  srcFiles: srcFiles.map((file) => file.filename),
367
372
  buildFiles: buildFiles.map((file) => file.filename),
368
373
  registeredComponents: componentConfigs,
@@ -376,15 +381,15 @@ You can reduce your component bundle size by uploading static assets to a separa
376
381
  }
377
382
  }
378
383
  catch (e) {
379
- if (e instanceof axios_1.AxiosError && ((_a = e.response) === null || _a === void 0 ? void 0 : _a.status) === 413) {
384
+ if (e instanceof axios_1.AxiosError && e.response?.status === 413) {
380
385
  throw new Error(`Could not upload application components, file size limit exceeded`);
381
386
  }
382
387
  else {
383
388
  let message;
384
389
  if (e instanceof axios_1.AxiosError) {
385
- message = (((_d = (_c = (_b = e.response) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.responseMeta) === null || _d === void 0 ? void 0 : _d.message) ||
386
- ((_e = e.response) === null || _e === void 0 ? void 0 : _e.data) ||
387
- ((_f = e.response) === null || _f === void 0 ? void 0 : _f.statusText));
390
+ message = (e.response?.data?.responseMeta?.message ||
391
+ e.response?.data ||
392
+ e.response?.statusText);
388
393
  }
389
394
  else {
390
395
  message = e.message;
@@ -398,7 +403,6 @@ You can reduce your component bundle size by uploading static assets to a separa
398
403
  }
399
404
  exports.uploadComponents = uploadComponents;
400
405
  async function fetchCurrentUser(cliVersion, token, superblocksBaseUrl) {
401
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
402
406
  try {
403
407
  const config = {
404
408
  method: "get",
@@ -416,26 +420,31 @@ async function fetchCurrentUser(cliVersion, token, superblocksBaseUrl) {
416
420
  let message;
417
421
  if (e instanceof axios_1.AxiosError) {
418
422
  message =
419
- (_j = (_h = (_f = (_d = (_c = (_b = (_a = e.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.responseMeta) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : JSON.stringify((_e = e.response) === null || _e === void 0 ? void 0 : _e.data)) !== null && _f !== void 0 ? _f : (_g = e.response) === null || _g === void 0 ? void 0 : _g.statusText) !== null && _h !== void 0 ? _h : e === null || e === void 0 ? void 0 : e.message) !== null && _j !== void 0 ? _j : `${e}`;
423
+ e.response?.data?.responseMeta?.message ??
424
+ JSON.stringify(e.response?.data) ??
425
+ e.response?.statusText ??
426
+ e?.message ??
427
+ `${e}`;
420
428
  }
421
429
  else {
422
- message = `${(e === null || e === void 0 ? void 0 : e.message) ? e === null || e === void 0 ? void 0 : e.message : e}`;
430
+ message = `${e?.message ? e?.message : e}`;
423
431
  }
424
432
  throw new Error(`Could not fetch current user: ${message}`);
425
433
  }
426
434
  }
427
435
  exports.fetchCurrentUser = fetchCurrentUser;
428
436
  async function pushApplication({ cliVersion, applicationId, token, superblocksBaseUrl, applicationConfig, branch, injectedHeaders = {}, }) {
429
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
430
437
  const serverURL = new URL(`${BASE_SERVER_PUBLIC_API_URL}/applications/${applicationId}/branches/${encodeURIComponent(branch)}/push`, superblocksBaseUrl);
431
438
  let serverResponse;
432
439
  try {
433
440
  const userMe = await fetchCurrentUser(cliVersion, token, superblocksBaseUrl);
434
441
  const organization = userMe.organizations[0];
435
- if (organization.agentType == types_1.AgentType.ONPREMISE && (0, flag_1.signingEnabled)(userMe.flagBootstrap)) {
436
- const agentUrls = (0, utils_1.getAgentUrls)(userMe.agents, organization.agentType);
442
+ if (organization.agentType == types_1.AgentType.ONPREMISE &&
443
+ (0, flag_1.signingEnabled)(userMe.flagBootstrap)) {
444
+ const profile = process.env.SUPERBLOCKS_PROFILE;
445
+ const agentUrl = await (0, utils_1.getAgentUrl)(userMe.agents, organization.agentType, profile);
437
446
  const socket = await (0, socket_1.connectToISocketRPCServer)({
438
- agentUrls,
447
+ agentUrl,
439
448
  superblocksBaseUrl,
440
449
  token,
441
450
  });
@@ -467,32 +476,34 @@ async function pushApplication({ cliVersion, applicationId, token, superblocksBa
467
476
  }
468
477
  catch (e) {
469
478
  if (axios_1.default.isAxiosError(e)) {
470
- const respCode = (_d = (_c = (_b = (_a = e.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.responseMeta) === null || _c === void 0 ? void 0 : _c.status) !== null && _d !== void 0 ? _d : (_e = e.response) === null || _e === void 0 ? void 0 : _e.status;
479
+ const respCode = e.response?.data?.responseMeta?.status ?? e.response?.status;
471
480
  if (respCode === 405) {
472
481
  throw new errors_1.BranchNotCheckedOutError(`Branch ${branch} is not checked out`);
473
482
  }
474
483
  else if (respCode === 409) {
475
484
  throw new errors_1.CommitAlreadyExistsError(`Commit ${applicationConfig.commitId} already exists`);
476
485
  }
477
- const message = (_l = (_j = (_h = (_g = (_f = e.response) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.responseMeta) === null || _h === void 0 ? void 0 : _h.message) !== null && _j !== void 0 ? _j : JSON.stringify((_k = e.response) === null || _k === void 0 ? void 0 : _k.data)) !== null && _l !== void 0 ? _l : (_m = e.response) === null || _m === void 0 ? void 0 : _m.statusText;
486
+ const message = e.response?.data?.responseMeta?.message ??
487
+ JSON.stringify(e.response?.data) ??
488
+ e.response?.statusText;
478
489
  throw new Error(`Could not push application ${message ? "\n" + message : ""}`);
479
490
  }
480
491
  throw new Error(`Could not push application ${e.message ? "\n" + e.message : ""}`);
481
492
  }
482
- return (_o = serverResponse === null || serverResponse === void 0 ? void 0 : serverResponse.data) === null || _o === void 0 ? void 0 : _o.data;
493
+ return serverResponse?.data?.data;
483
494
  }
484
495
  exports.pushApplication = pushApplication;
485
496
  async function pushApi({ cliVersion, apiId, token, superblocksBaseUrl, apiConfig, branch, injectedHeaders = {}, }) {
486
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
487
497
  const serverURL = new URL(`${BASE_SERVER_PUBLIC_API_URL}/apis/${apiId}/branches/${encodeURIComponent(branch)}/push`, superblocksBaseUrl);
488
498
  let serverResponse;
489
499
  try {
490
500
  const userMe = await fetchCurrentUser(cliVersion, token, superblocksBaseUrl);
491
501
  const organization = userMe.organizations[0];
492
- if (organization.agentType == types_1.AgentType.ONPREMISE && (0, flag_1.signingEnabled)(userMe.flagBootstrap)) {
493
- const agentUrls = (0, utils_1.getAgentUrls)(userMe.agents, organization.agentType);
502
+ if (organization.agentType == types_1.AgentType.ONPREMISE &&
503
+ (0, flag_1.signingEnabled)(userMe.flagBootstrap)) {
504
+ const agentUrl = await (0, utils_1.getAgentUrl)(userMe.agents, organization.agentType);
494
505
  const socket = await (0, socket_1.connectToISocketRPCServer)({
495
- agentUrls,
506
+ agentUrl,
496
507
  superblocksBaseUrl,
497
508
  token,
498
509
  });
@@ -522,17 +533,19 @@ async function pushApi({ cliVersion, apiId, token, superblocksBaseUrl, apiConfig
522
533
  }
523
534
  catch (e) {
524
535
  if (axios_1.default.isAxiosError(e)) {
525
- if (((_c = (_b = (_a = e.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.responseMeta) === null || _c === void 0 ? void 0 : _c.status) === 405) {
536
+ if (e.response?.data?.responseMeta?.status === 405) {
526
537
  throw new errors_1.BranchNotCheckedOutError(`Branch ${branch} is not checked out`);
527
538
  }
528
- else if (((_f = (_e = (_d = e.response) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.responseMeta) === null || _f === void 0 ? void 0 : _f.status) === 409) {
539
+ else if (e.response?.data?.responseMeta?.status === 409) {
529
540
  throw new errors_1.CommitAlreadyExistsError(`Commit ${apiConfig.commitId} already exists`);
530
541
  }
531
- const message = (_m = (_k = (_j = (_h = (_g = e.response) === null || _g === void 0 ? void 0 : _g.data) === null || _h === void 0 ? void 0 : _h.responseMeta) === null || _j === void 0 ? void 0 : _j.message) !== null && _k !== void 0 ? _k : JSON.stringify((_l = e.response) === null || _l === void 0 ? void 0 : _l.data)) !== null && _m !== void 0 ? _m : (_o = e.response) === null || _o === void 0 ? void 0 : _o.statusText;
542
+ const message = e.response?.data?.responseMeta?.message ??
543
+ JSON.stringify(e.response?.data) ??
544
+ e.response?.statusText;
532
545
  throw new Error(`Could not push api ${message ? "\n" + message : ""}`);
533
546
  }
534
547
  throw new Error(`Could not push api ${e.message ? "\n" + e.message : ""}`);
535
548
  }
536
- return (_p = serverResponse === null || serverResponse === void 0 ? void 0 : serverResponse.data) === null || _p === void 0 ? void 0 : _p.data;
549
+ return serverResponse?.data?.data;
537
550
  }
538
551
  exports.pushApi = pushApi;
package/dist/flag.js CHANGED
@@ -2,7 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.signingEnabled = void 0;
4
4
  const signingEnabled = (flags) => {
5
- var _a;
6
- return (_a = flags["ui.enable-resource-signing"]) !== null && _a !== void 0 ? _a : false;
5
+ return flags["ui.enable-resource-signing"] ?? false;
7
6
  };
8
7
  exports.signingEnabled = signingEnabled;
@@ -98,8 +98,8 @@ export interface ServerMethods {
98
98
  };
99
99
  };
100
100
  }
101
- export declare function createRequestHandlers({ agentUrls, token, }: {
101
+ export declare function createRequestHandlers({ agentUrl, token, }: {
102
102
  token: string;
103
- agentUrls: string[];
103
+ agentUrl?: string;
104
104
  }): MethodHandlers<ClientMethods, ServerMethods, unknown>;
105
105
  export {};
@@ -2,14 +2,17 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createRequestHandlers = void 0;
4
4
  const signing_1 = require("./signing");
5
- function createRequestHandlers({ agentUrls, token, }) {
5
+ function createRequestHandlers({ agentUrl, token, }) {
6
6
  const requestHandlers = {
7
7
  v1: {
8
8
  signing: {
9
9
  signApplication: [
10
10
  async ({ branchName, toSign, }) => {
11
+ if (!agentUrl) {
12
+ throw new Error("Agent url not specified. This shouldn't happen.");
13
+ }
11
14
  const signature = await (0, signing_1.signResource)({
12
- agentUrls,
15
+ agentUrl,
13
16
  token: token,
14
17
  branchName,
15
18
  resource: {
@@ -25,8 +28,11 @@ function createRequestHandlers({ agentUrls, token, }) {
25
28
  async ({ branchName, toSign, }) => {
26
29
  const signatures = [];
27
30
  for (const { apiPb } of toSign) {
31
+ if (!agentUrl) {
32
+ throw new Error("Agent url not specified. This shouldn't happen.");
33
+ }
28
34
  const signature = await (0, signing_1.signResource)({
29
- agentUrls,
35
+ agentUrl,
30
36
  token: token,
31
37
  branchName,
32
38
  resource: { api: apiPb },
@@ -39,8 +45,11 @@ function createRequestHandlers({ agentUrls, token, }) {
39
45
  verifyApplication: [
40
46
  async ({ branchName, toVerify, }) => {
41
47
  try {
48
+ if (!agentUrl) {
49
+ throw new Error("Agent url not specified. This shouldn't happen.");
50
+ }
42
51
  await (0, signing_1.verifyResources)({
43
- agentUrls,
52
+ agentUrl,
44
53
  token,
45
54
  branchName,
46
55
  resources: [
@@ -62,8 +71,11 @@ function createRequestHandlers({ agentUrls, token, }) {
62
71
  verifyApi: [
63
72
  async ({ branchName, toVerify, }) => {
64
73
  try {
74
+ if (!agentUrl) {
75
+ throw new Error("Agent url not specified. This shouldn't happen.");
76
+ }
65
77
  await (0, signing_1.verifyResources)({
66
- agentUrls,
78
+ agentUrl,
67
79
  token,
68
80
  branchName,
69
81
  resources: toVerify.map(({ apiPb }) => ({
@@ -2,10 +2,10 @@
2
2
  import WebSocket from "isomorphic-ws";
3
3
  import { ServerMethods } from "./handlers";
4
4
  export type StdISocketRPCClient = ISocketClient<ServerMethods>;
5
- export declare function connectToISocketRPCServer({ superblocksBaseUrl, agentUrls, token, }: {
5
+ export declare function connectToISocketRPCServer({ superblocksBaseUrl, agentUrl, token, }: {
6
6
  superblocksBaseUrl: string;
7
- agentUrls: string[];
8
7
  token: string;
8
+ agentUrl?: string;
9
9
  }): Promise<StdISocketRPCClient>;
10
10
  export declare function connectISocket<CallableMethods, ImplementedMethods, RequestContext = never>(wsUrl: string, authorization: string | undefined, requestHandlers: MethodHandlers<ImplementedMethods, CallableMethods, RequestContext>): Promise<ISocketClient<CallableMethods>>;
11
11
  export declare function connectWebSocket(wsUrl: string): Promise<WebSocket>;
@@ -5,9 +5,9 @@ const tslib_1 = require("tslib");
5
5
  const isomorphic_ws_1 = tslib_1.__importDefault(require("isomorphic-ws"));
6
6
  const handlers_1 = require("./handlers");
7
7
  const socket_1 = require("./socket");
8
- async function connectToISocketRPCServer({ superblocksBaseUrl, agentUrls, token, }) {
8
+ async function connectToISocketRPCServer({ superblocksBaseUrl, agentUrl, token, }) {
9
9
  const requestHandlers = (0, handlers_1.createRequestHandlers)({
10
- agentUrls,
10
+ agentUrl,
11
11
  token,
12
12
  });
13
13
  const authorization = `Bearer ${token}`;
@@ -1,13 +1,13 @@
1
1
  import { ApiResource, GenericResource, Signature } from "../types";
2
- export declare function signResource({ token, branchName, resource, agentUrls, }: {
2
+ export declare function signResource({ token, branchName, resource, agentUrl, }: {
3
3
  token: string;
4
4
  branchName: string;
5
5
  resource: ApiResource | GenericResource;
6
- agentUrls: string[];
6
+ agentUrl: string;
7
7
  }): Promise<Signature>;
8
- export declare function verifyResources({ agentUrls, token, branchName, resources, }: {
8
+ export declare function verifyResources({ agentUrl, token, branchName, resources, }: {
9
9
  resources: Array<GenericResource | ApiResource>;
10
10
  token: string;
11
11
  branchName: string;
12
- agentUrls: string[];
12
+ agentUrl: string;
13
13
  }): Promise<void>;
@@ -4,9 +4,9 @@ exports.verifyResources = exports.signResource = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const axios_1 = tslib_1.__importDefault(require("axios"));
6
6
  const utils_1 = require("../utils");
7
- async function signResource({ token, branchName, resource, agentUrls, }) {
7
+ async function signResource({ token, branchName, resource, agentUrl, }) {
8
8
  const requestResource = {
9
- branchName: branchName !== null && branchName !== void 0 ? branchName : "main",
9
+ branchName: branchName ?? "main",
10
10
  };
11
11
  if (resource.api) {
12
12
  // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
@@ -15,67 +15,56 @@ async function signResource({ token, branchName, resource, agentUrls, }) {
15
15
  else {
16
16
  requestResource.literal = resource.literal;
17
17
  }
18
- try {
19
- const resp = await callAgentFallBack({
20
- baseUrls: agentUrls,
21
- path: "v1/signature/sign",
22
- method: "post",
23
- token: token,
24
- data: { resource: requestResource },
25
- });
26
- return resp.signature;
27
- }
28
- catch (e) {
29
- throw new Error("No agents available to sign the resource");
30
- }
18
+ const resp = await callAgent({
19
+ baseUrl: agentUrl,
20
+ path: "v1/signature/sign",
21
+ method: "post",
22
+ token: token,
23
+ data: { resource: requestResource },
24
+ });
25
+ return resp.signature;
31
26
  }
32
27
  exports.signResource = signResource;
33
- async function verifyResources({ agentUrls, token, branchName, resources, }) {
34
- try {
35
- await callAgentFallBack({
36
- baseUrls: agentUrls,
37
- path: "v1/signature/verify",
38
- method: "post",
39
- token: token,
40
- data: {
41
- resources: resources.map((res) => {
42
- if (res.api) {
43
- return {
44
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
45
- api: (0, utils_1.getSanitizedApi)(res.api),
46
- branchName: branchName !== null && branchName !== void 0 ? branchName : "main",
47
- };
48
- }
28
+ async function verifyResources({ agentUrl, token, branchName, resources, }) {
29
+ await callAgent({
30
+ baseUrl: agentUrl,
31
+ path: "v1/signature/verify",
32
+ method: "post",
33
+ token: token,
34
+ data: {
35
+ resources: resources.map((res) => {
36
+ if (res.api) {
49
37
  return {
50
- ...res,
51
- branchName: branchName !== null && branchName !== void 0 ? branchName : "main",
38
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
39
+ api: (0, utils_1.getSanitizedApi)(res.api),
40
+ branchName: branchName ?? "main",
52
41
  };
53
- }),
54
- },
55
- });
56
- }
57
- catch (e) {
58
- throw new Error("No agents available to verify the resource");
59
- }
42
+ }
43
+ return {
44
+ ...res,
45
+ branchName: branchName ?? "main",
46
+ };
47
+ }),
48
+ },
49
+ });
60
50
  }
61
51
  exports.verifyResources = verifyResources;
62
- async function callAgentFallBack({ baseUrls, path, method, token, data, }) {
63
- for (const baseUrl of baseUrls) {
64
- try {
65
- const url = new URL(path, baseUrl);
66
- const config = {
67
- url: url.toString(),
68
- method: method,
69
- headers: {
70
- Authorization: "Bearer " + token,
71
- },
72
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
73
- data: data,
74
- };
75
- const resp = await (0, axios_1.default)(config);
76
- return resp.data;
77
- }
78
- catch (e) { }
52
+ async function callAgent({ baseUrl, path, method, token, data, }) {
53
+ try {
54
+ const url = new URL(path, baseUrl);
55
+ const config = {
56
+ url: url.toString(),
57
+ method: method,
58
+ headers: {
59
+ Authorization: "Bearer " + token,
60
+ },
61
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
62
+ data: data,
63
+ };
64
+ const resp = await (0, axios_1.default)(config);
65
+ return resp.data;
66
+ }
67
+ catch (error) {
68
+ throw new Error(`Failed to request the agent ${baseUrl}. Error: ${error}`);
79
69
  }
80
- throw new Error("Failed to request ");
81
70
  }
package/dist/utils.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  import { Agent, AgentType, Api } from "./types";
2
- export declare function getAgentUrls(agents: Agent[], agentType: AgentType): string[];
2
+ export declare function getAgentUrl(agents: Agent[], agentType: AgentType, profile?: string, healthCheck?: boolean): Promise<string>;
3
3
  export declare const sanitizeV2RequestBody: (apiBody: Record<string, unknown>) => Record<string, unknown>;
4
4
  export declare const getSanitizedApi: (api: Api) => any;
package/dist/utils.js CHANGED
@@ -1,12 +1,43 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getSanitizedApi = exports.sanitizeV2RequestBody = exports.getAgentUrls = void 0;
3
+ exports.getSanitizedApi = exports.sanitizeV2RequestBody = exports.getAgentUrl = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const axios_1 = tslib_1.__importDefault(require("axios"));
4
6
  const types_1 = require("./types");
5
- function getAgentUrls(agents, agentType) {
6
- const filtered = agents.filter((a) => a.type === agentType && a.status === types_1.AgentStatus.ACTIVE);
7
- return filtered.map((f) => f.url);
7
+ async function getAgentUrl(agents, agentType, profile, healthCheck = true) {
8
+ let filtered = agents.filter((a) => a.type === agentType && a.status === types_1.AgentStatus.ACTIVE);
9
+ if (profile) {
10
+ filtered = agents.filter((a) => a.tags.profile &&
11
+ (a.tags.profile.includes("*") || a.tags.profile.includes(profile)));
12
+ }
13
+ if (healthCheck) {
14
+ const coroutines = [];
15
+ for (const agent of filtered) {
16
+ const p = (async () => {
17
+ const url = new URL("health", agent.url);
18
+ const config = {
19
+ url: url.toString(),
20
+ method: "get",
21
+ headers: {},
22
+ };
23
+ await (0, axios_1.default)(config);
24
+ return agent.url;
25
+ })();
26
+ coroutines.push(p);
27
+ }
28
+ try {
29
+ return await Promise.any(coroutines);
30
+ }
31
+ catch (e) {
32
+ throw new Error("No available agents");
33
+ }
34
+ }
35
+ else {
36
+ const randomIndex = Math.floor(Math.random() * filtered.length);
37
+ return filtered[randomIndex].url;
38
+ }
8
39
  }
9
- exports.getAgentUrls = getAgentUrls;
40
+ exports.getAgentUrl = getAgentUrl;
10
41
  const sanitizeV2RequestBody = (apiBody) => {
11
42
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
12
43
  const traverseJSON = (obj) => {
@@ -26,8 +57,7 @@ const sanitizeV2RequestBody = (apiBody) => {
26
57
  };
27
58
  exports.sanitizeV2RequestBody = sanitizeV2RequestBody;
28
59
  const getSanitizedApi = (api) => {
29
- var _a, _b;
30
- const sanitizedBlocks = (_b = ((_a = api.blocks) !== null && _a !== void 0 ? _a : [])) === null || _b === void 0 ? void 0 : _b.map((block) => (0, exports.sanitizeV2RequestBody)(block));
60
+ const sanitizedBlocks = (api.blocks ?? [])?.map((block) => (0, exports.sanitizeV2RequestBody)(block));
31
61
  return {
32
62
  ...api,
33
63
  blocks: sanitizedBlocks,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@superblocksteam/sdk",
3
- "version": "1.5.0",
3
+ "version": "1.5.1",
4
4
  "description": "Superblocks JS SDK",
5
5
  "main": "./dist/index.js",
6
6
  "exports": {
@@ -31,7 +31,7 @@
31
31
  "typescript": "^5.1.3"
32
32
  },
33
33
  "dependencies": {
34
- "@superblocksteam/util": "1.5.0",
34
+ "@superblocksteam/util": "1.5.1",
35
35
  "axios": "^1.3.5",
36
36
  "isomorphic-ws": "^5.0.0"
37
37
  },
package/src/client.ts CHANGED
@@ -17,7 +17,7 @@ import { BranchNotCheckedOutError, CommitAlreadyExistsError } from "./errors";
17
17
  import { signingEnabled } from "./flag";
18
18
  import { connectToISocketRPCServer } from "./socket";
19
19
  import { AgentType, RemoteCommitDto, UserMeDto } from "./types";
20
- import { getAgentUrls } from "./utils";
20
+ import { getAgentUrl } from "./utils";
21
21
 
22
22
  const BASE_BUCKETEER_URL = "api";
23
23
  const BASE_SERVER_PUBLIC_API_URL = "api/v1/public";
@@ -422,10 +422,18 @@ export async function registerComponents(
422
422
  superblocksBaseUrl
423
423
  );
424
424
  const organization = userMe.organizations[0];
425
- if (organization.agentType == AgentType.ONPREMISE && signingEnabled(userMe.flagBootstrap)) {
426
- const agentUrls = getAgentUrls(userMe.agents, organization.agentType);
425
+ if (
426
+ organization.agentType == AgentType.ONPREMISE &&
427
+ signingEnabled(userMe.flagBootstrap)
428
+ ) {
429
+ const profile = process.env.SUPERBLOCKS_PROFILE;
430
+ const agentUrl = await getAgentUrl(
431
+ userMe.agents,
432
+ organization.agentType,
433
+ profile
434
+ );
427
435
  const socket = await connectToISocketRPCServer({
428
- agentUrls,
436
+ agentUrl,
429
437
  superblocksBaseUrl,
430
438
  token,
431
439
  });
@@ -554,7 +562,7 @@ You can reduce your component bundle size by uploading static assets to a separa
554
562
  [CLI_VERSION_HEADER]: cliVersion,
555
563
  [COMPONENT_EVENT_HEADER]: ComponentEvent.UPLOAD,
556
564
  [SUPERBLOCKS_URL_HEADER]: superblocksBaseUrl,
557
- ...formHeaders,
565
+ ...formHeaders,
558
566
  },
559
567
  };
560
568
 
@@ -566,13 +574,15 @@ You can reduce your component bundle size by uploading static assets to a separa
566
574
  superblocksBaseUrl
567
575
  );
568
576
  const organization = userMe.organizations[0];
569
- const signingRequired = organization.agentType == AgentType.ONPREMISE && signingEnabled(userMe.flagBootstrap);
570
- let agentUrls: string[] = [];
577
+ let agentUrl: string | undefined;
578
+ const signingRequired =
579
+ organization.agentType == AgentType.ONPREMISE &&
580
+ signingEnabled(userMe.flagBootstrap);
571
581
  if (signingRequired) {
572
- agentUrls = getAgentUrls(userMe.agents, organization.agentType);
582
+ agentUrl = await getAgentUrl(userMe.agents, organization.agentType);
573
583
  }
574
584
  const socket = await connectToISocketRPCServer({
575
- agentUrls,
585
+ agentUrl,
576
586
  superblocksBaseUrl,
577
587
  token,
578
588
  });
@@ -680,10 +690,18 @@ export async function pushApplication({
680
690
  superblocksBaseUrl
681
691
  );
682
692
  const organization = userMe.organizations[0];
683
- if (organization.agentType == AgentType.ONPREMISE && signingEnabled(userMe.flagBootstrap)) {
684
- const agentUrls = getAgentUrls(userMe.agents, organization.agentType);
693
+ if (
694
+ organization.agentType == AgentType.ONPREMISE &&
695
+ signingEnabled(userMe.flagBootstrap)
696
+ ) {
697
+ const profile = process.env.SUPERBLOCKS_PROFILE;
698
+ const agentUrl = await getAgentUrl(
699
+ userMe.agents,
700
+ organization.agentType,
701
+ profile
702
+ );
685
703
  const socket = await connectToISocketRPCServer({
686
- agentUrls,
704
+ agentUrl,
687
705
  superblocksBaseUrl,
688
706
  token,
689
707
  });
@@ -775,10 +793,13 @@ export async function pushApi({
775
793
  superblocksBaseUrl
776
794
  );
777
795
  const organization = userMe.organizations[0];
778
- if (organization.agentType == AgentType.ONPREMISE && signingEnabled(userMe.flagBootstrap)) {
779
- const agentUrls = getAgentUrls(userMe.agents, organization.agentType);
796
+ if (
797
+ organization.agentType == AgentType.ONPREMISE &&
798
+ signingEnabled(userMe.flagBootstrap)
799
+ ) {
800
+ const agentUrl = await getAgentUrl(userMe.agents, organization.agentType);
780
801
  const socket = await connectToISocketRPCServer({
781
- agentUrls,
802
+ agentUrl,
782
803
  superblocksBaseUrl,
783
804
  token,
784
805
  });
@@ -117,11 +117,11 @@ export interface ServerMethods {
117
117
  }
118
118
 
119
119
  export function createRequestHandlers({
120
- agentUrls,
120
+ agentUrl,
121
121
  token,
122
122
  }: {
123
123
  token: string;
124
- agentUrls: string[];
124
+ agentUrl?: string;
125
125
  }) {
126
126
  const requestHandlers: MethodHandlers<ClientMethods, ServerMethods, unknown> =
127
127
  {
@@ -135,8 +135,13 @@ export function createRequestHandlers({
135
135
  branchName: string;
136
136
  toSign: AppToSign;
137
137
  }) => {
138
+ if (!agentUrl) {
139
+ throw new Error(
140
+ "Agent url not specified. This shouldn't happen."
141
+ );
142
+ }
138
143
  const signature = await signResource({
139
- agentUrls,
144
+ agentUrl,
140
145
  token: token,
141
146
  branchName,
142
147
  resource: {
@@ -158,8 +163,13 @@ export function createRequestHandlers({
158
163
  }) => {
159
164
  const signatures: Signature[] = [];
160
165
  for (const { apiPb } of toSign) {
166
+ if (!agentUrl) {
167
+ throw new Error(
168
+ "Agent url not specified. This shouldn't happen."
169
+ );
170
+ }
161
171
  const signature = await signResource({
162
- agentUrls,
172
+ agentUrl,
163
173
  token: token,
164
174
  branchName,
165
175
  resource: { api: apiPb },
@@ -178,8 +188,13 @@ export function createRequestHandlers({
178
188
  toVerify: AppToVerify;
179
189
  }) => {
180
190
  try {
191
+ if (!agentUrl) {
192
+ throw new Error(
193
+ "Agent url not specified. This shouldn't happen."
194
+ );
195
+ }
181
196
  await verifyResources({
182
- agentUrls,
197
+ agentUrl,
183
198
  token,
184
199
  branchName,
185
200
  resources: [
@@ -207,8 +222,13 @@ export function createRequestHandlers({
207
222
  toVerify: ApiToVerify[];
208
223
  }) => {
209
224
  try {
225
+ if (!agentUrl) {
226
+ throw new Error(
227
+ "Agent url not specified. This shouldn't happen."
228
+ );
229
+ }
210
230
  await verifyResources({
211
- agentUrls,
231
+ agentUrl,
212
232
  token,
213
233
  branchName,
214
234
  resources: toVerify.map(({ apiPb }) => ({
@@ -10,15 +10,15 @@ export type StdISocketRPCClient = ISocketClient<ServerMethods>;
10
10
 
11
11
  export async function connectToISocketRPCServer({
12
12
  superblocksBaseUrl,
13
- agentUrls,
13
+ agentUrl,
14
14
  token,
15
15
  }: {
16
16
  superblocksBaseUrl: string;
17
- agentUrls: string[];
18
17
  token: string;
18
+ agentUrl?: string;
19
19
  }): Promise<StdISocketRPCClient> {
20
20
  const requestHandlers = createRequestHandlers({
21
- agentUrls,
21
+ agentUrl,
22
22
  token,
23
23
  });
24
24
  const authorization = `Bearer ${token}`;
@@ -11,12 +11,12 @@ export async function signResource({
11
11
  token,
12
12
  branchName,
13
13
  resource,
14
- agentUrls,
14
+ agentUrl,
15
15
  }: {
16
16
  token: string;
17
17
  branchName: string;
18
18
  resource: ApiResource | GenericResource;
19
- agentUrls: string[];
19
+ agentUrl: string;
20
20
  }): Promise<Signature> {
21
21
  const requestResource: Record<string, any> = {
22
22
  branchName: branchName ?? "main",
@@ -28,22 +28,18 @@ export async function signResource({
28
28
  requestResource.literal = (resource as GenericResource).literal;
29
29
  }
30
30
 
31
- try {
32
- const resp = await callAgentFallBack<SignatureResponse>({
33
- baseUrls: agentUrls,
34
- path: "v1/signature/sign",
35
- method: "post",
36
- token: token,
37
- data: { resource: requestResource },
38
- });
39
- return resp.signature;
40
- } catch (e) {
41
- throw new Error("No agents available to sign the resource");
42
- }
31
+ const resp = await callAgent<SignatureResponse>({
32
+ baseUrl: agentUrl,
33
+ path: "v1/signature/sign",
34
+ method: "post",
35
+ token: token,
36
+ data: { resource: requestResource },
37
+ });
38
+ return resp.signature;
43
39
  }
44
40
 
45
41
  export async function verifyResources({
46
- agentUrls,
42
+ agentUrl,
47
43
  token,
48
44
  branchName,
49
45
  resources,
@@ -51,63 +47,58 @@ export async function verifyResources({
51
47
  resources: Array<GenericResource | ApiResource>;
52
48
  token: string;
53
49
  branchName: string;
54
- agentUrls: string[];
50
+ agentUrl: string;
55
51
  }): Promise<void> {
56
- try {
57
- await callAgentFallBack<{ keyId: string }>({
58
- baseUrls: agentUrls,
59
- path: "v1/signature/verify",
60
- method: "post",
61
- token: token,
62
- data: {
63
- resources: resources.map((res) => {
64
- if ((res as ApiResource).api) {
65
- return {
66
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
67
- api: getSanitizedApi((res as ApiResource).api),
68
- branchName: branchName ?? "main",
69
- };
70
- }
52
+ await callAgent<{ keyId: string }>({
53
+ baseUrl: agentUrl,
54
+ path: "v1/signature/verify",
55
+ method: "post",
56
+ token: token,
57
+ data: {
58
+ resources: resources.map((res) => {
59
+ if ((res as ApiResource).api) {
71
60
  return {
72
- ...res,
61
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
62
+ api: getSanitizedApi((res as ApiResource).api),
73
63
  branchName: branchName ?? "main",
74
64
  };
75
- }),
76
- },
77
- });
78
- } catch (e) {
79
- throw new Error("No agents available to verify the resource");
80
- }
65
+ }
66
+ return {
67
+ ...res,
68
+ branchName: branchName ?? "main",
69
+ };
70
+ }),
71
+ },
72
+ });
81
73
  }
82
74
 
83
- async function callAgentFallBack<T>({
84
- baseUrls,
75
+ async function callAgent<T>({
76
+ baseUrl,
85
77
  path,
86
78
  method,
87
79
  token,
88
80
  data,
89
81
  }: {
90
- baseUrls: string[];
82
+ baseUrl: string;
91
83
  path: string;
92
84
  method: Method;
93
85
  token: string;
94
86
  data: any;
95
87
  }): Promise<T> {
96
- for (const baseUrl of baseUrls) {
97
- try {
98
- const url = new URL(path, baseUrl);
99
- const config: AxiosRequestConfig = {
100
- url: url.toString(),
101
- method: method,
102
- headers: {
103
- Authorization: "Bearer " + token,
104
- },
105
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
106
- data: data,
107
- };
108
- const resp = await axios<T>(config);
109
- return resp.data;
110
- } catch (e) {}
88
+ try {
89
+ const url = new URL(path, baseUrl);
90
+ const config: AxiosRequestConfig = {
91
+ url: url.toString(),
92
+ method: method,
93
+ headers: {
94
+ Authorization: "Bearer " + token,
95
+ },
96
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
97
+ data: data,
98
+ };
99
+ const resp = await axios<T>(config);
100
+ return resp.data;
101
+ } catch (error) {
102
+ throw new Error(`Failed to request the agent ${baseUrl}. Error: ${error}`);
111
103
  }
112
- throw new Error("Failed to request ");
113
104
  }
package/src/utils.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import axios, { AxiosRequestConfig } from "axios";
1
2
  import {
2
3
  Agent,
3
4
  AgentStatus,
@@ -7,11 +8,46 @@ import {
7
8
  transcribeAudioToTextTranslateToEnglishTruthyValues,
8
9
  } from "./types";
9
10
 
10
- export function getAgentUrls(agents: Agent[], agentType: AgentType): string[] {
11
- const filtered = agents.filter(
11
+ export async function getAgentUrl(
12
+ agents: Agent[],
13
+ agentType: AgentType,
14
+ profile?: string,
15
+ healthCheck = true
16
+ ): Promise<string> {
17
+ let filtered = agents.filter(
12
18
  (a) => a.type === agentType && a.status === AgentStatus.ACTIVE
13
19
  );
14
- return filtered.map((f) => f.url);
20
+ if (profile) {
21
+ filtered = agents.filter(
22
+ (a) =>
23
+ a.tags.profile &&
24
+ (a.tags.profile.includes("*") || a.tags.profile.includes(profile))
25
+ );
26
+ }
27
+ if (healthCheck) {
28
+ const coroutines: Promise<string>[] = [];
29
+ for (const agent of filtered) {
30
+ const p: Promise<string> = (async () => {
31
+ const url = new URL("health", agent.url);
32
+ const config: AxiosRequestConfig = {
33
+ url: url.toString(),
34
+ method: "get",
35
+ headers: {},
36
+ };
37
+ await axios(config);
38
+ return agent.url;
39
+ })();
40
+ coroutines.push(p);
41
+ }
42
+ try {
43
+ return await Promise.any(coroutines);
44
+ } catch (e) {
45
+ throw new Error("No available agents");
46
+ }
47
+ } else {
48
+ const randomIndex = Math.floor(Math.random() * filtered.length);
49
+ return filtered[randomIndex].url;
50
+ }
15
51
  }
16
52
 
17
53
  export const sanitizeV2RequestBody = (
package/tsconfig.json CHANGED
@@ -6,7 +6,7 @@
6
6
  "outDir": "dist",
7
7
  "rootDir": "src",
8
8
  "strict": true,
9
- "target": "es2019",
9
+ "target": "es2021",
10
10
  "esModuleInterop": true,
11
11
  "skipLibCheck": true
12
12
  },