@mitralab.io/functions-sdk 0.1.1 → 0.2.0-beta.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/index.cjs CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,19 +17,92 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
21
31
  var index_exports = {};
22
32
  __export(index_exports, {
33
+ AgentTaskTurnError: () => import_sdk_core3.AgentTaskTurnError,
23
34
  MitraApiError: () => MitraApiError,
24
35
  MitraConfigurationError: () => MitraConfigurationError,
36
+ callIntegrationMitra: () => callIntegrationMitra2,
37
+ configureSdkMitra: () => configureSdkMitra3,
38
+ createAgentMitra: () => createAgentMitra2,
25
39
  createClient: () => createClient,
26
- createClientFromEnvironment: () => createClientFromEnvironment
40
+ createClientFromEnvironment: () => createClientFromEnvironment,
41
+ createIntegrationMitra: () => createIntegrationMitra2,
42
+ createJdbcConnectionMitra: () => createJdbcConnectionMitra2,
43
+ createMitraSdkInstance: () => createMitraSdkInstance2,
44
+ createOnlineTableMitra: () => createOnlineTableMitra2,
45
+ createProjectMitra: () => createProjectMitra2,
46
+ createRecordMitra: () => createRecordMitra2,
47
+ createRecordsBatchMitra: () => createRecordsBatchMitra2,
48
+ createServerFunctionMitra: () => createServerFunctionMitra2,
49
+ deleteAgentMitra: () => deleteAgentMitra2,
50
+ deleteIntegrationMitra: () => deleteIntegrationMitra2,
51
+ deleteJdbcConnectionMitra: () => deleteJdbcConnectionMitra2,
52
+ deleteOnlineTableMitra: () => deleteOnlineTableMitra2,
53
+ deleteRecordMitra: () => deleteRecordMitra2,
54
+ deleteServerFunctionMitra: () => deleteServerFunctionMitra2,
55
+ deployToS3Mitra: () => deployToS3Mitra2,
56
+ executePublicServerFunctionAsyncMitra: () => executePublicServerFunctionAsyncMitra2,
57
+ executeServerFunctionAsyncMitra: () => executeServerFunctionAsyncMitra2,
58
+ executeServerFunctionMitra: () => executeServerFunctionMitra2,
59
+ getAgentTaskMitra: () => getAgentTaskMitra2,
60
+ getDeployStatusMitra: () => getDeployStatusMitra2,
61
+ getGitConfigMitra: () => getGitConfigMitra2,
62
+ getIntegrationTemplateMitra: () => getIntegrationTemplateMitra2,
63
+ getProjectContextMitra: () => getProjectContextMitra2,
64
+ getProjectsMitra: () => getProjectsMitra2,
65
+ getRecordMitra: () => getRecordMitra2,
66
+ getServerFunctionExecutionMitra: () => getServerFunctionExecutionMitra2,
67
+ inviteUserMitra: () => inviteUserMitra2,
68
+ listAgentsMitra: () => listAgentsMitra2,
69
+ listIntegrationTemplatesMitra: () => listIntegrationTemplatesMitra2,
70
+ listIntegrationsMitra: () => listIntegrationsMitra2,
71
+ listJdbcConnectionsMitra: () => listJdbcConnectionsMitra2,
72
+ listOnlineTablesMitra: () => listOnlineTablesMitra2,
73
+ listProjectsMitra: () => listProjectsMitra2,
74
+ listRecordsMitra: () => listRecordsMitra2,
75
+ listServerFunctionsMitra: () => listServerFunctionsMitra2,
76
+ listTablesMitra: () => listTablesMitra2,
77
+ manageAgentChatMitra: () => manageAgentChatMitra2,
78
+ manageAgentConnectionMitra: () => manageAgentConnectionMitra2,
79
+ manageAgentCredentialMitra: () => manageAgentCredentialMitra2,
80
+ patchRecordMitra: () => patchRecordMitra2,
81
+ readAgentMitra: () => readAgentMitra2,
82
+ readServerFunctionMitra: () => readServerFunctionMitra2,
83
+ resolveProjectId: () => resolveProjectId2,
84
+ runDdlMitra: () => runDdlMitra2,
85
+ runDmlMitra: () => runDmlMitra2,
86
+ runQueryMitra: () => runQueryMitra2,
87
+ stopServerFunctionExecutionMitra: () => stopServerFunctionExecutionMitra2,
88
+ testIntegrationByIdMitra: () => testIntegrationByIdMitra2,
89
+ testIntegrationMitra: () => testIntegrationMitra2,
90
+ togglePublicExecutionMitra: () => togglePublicExecutionMitra2,
91
+ unsubscribeUserMitra: () => unsubscribeUserMitra2,
92
+ updateAgentMitra: () => updateAgentMitra2,
93
+ updateIntegrationMitra: () => updateIntegrationMitra2,
94
+ updateJdbcConnectionMitra: () => updateJdbcConnectionMitra2,
95
+ updateOnlineTableMitra: () => updateOnlineTableMitra2,
96
+ updateProjectSettingsMitra: () => updateProjectSettingsMitra2,
97
+ updateRecordMitra: () => updateRecordMitra2,
98
+ updateServerFunctionMitra: () => updateServerFunctionMitra2
27
99
  });
28
100
  module.exports = __toCommonJS(index_exports);
29
101
 
30
102
  // src/client.ts
103
+ var import_sdk_core2 = require("@mitralab.io/sdk-core");
104
+
105
+ // src/agent-task-sse.ts
31
106
  var import_sdk_core = require("@mitralab.io/sdk-core");
32
107
 
33
108
  // src/errors.ts
@@ -54,74 +129,11 @@ var MitraApiError = class extends Error {
54
129
  }
55
130
  };
56
131
 
57
- // src/config.ts
58
- var DEFAULT_TIMEOUT_MS = 1e4;
59
- function readDefaultEnvironment() {
60
- return typeof process === "undefined" ? {} : process.env;
61
- }
62
- function requiredValue(value, name) {
63
- if (!value?.trim()) {
64
- throw new MitraConfigurationError(`${name} is required`);
65
- }
66
- return value.trim();
67
- }
68
- function removeTrailingSlashes(value) {
69
- let end = value.length;
70
- while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
71
- return value.slice(0, end);
72
- }
73
- function normalizeApiUrl(value) {
74
- let parsed;
75
- try {
76
- parsed = new URL(value);
77
- } catch {
78
- throw new MitraConfigurationError("apiUrl must be a valid HTTP or HTTPS URL");
79
- }
80
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
81
- throw new MitraConfigurationError("apiUrl must be a valid HTTP or HTTPS URL");
82
- }
83
- if (parsed.username || parsed.password || parsed.search || parsed.hash || value.includes("?") || value.includes("#")) {
84
- throw new MitraConfigurationError(
85
- "apiUrl must not include credentials, query parameters, or a fragment"
86
- );
87
- }
88
- return removeTrailingSlashes(parsed.toString());
89
- }
90
- function resolveConfig(config = {}, environment = readDefaultEnvironment()) {
91
- const apiUrl = normalizeApiUrl(
92
- requiredValue(config.apiUrl ?? environment.MITRA_API_URL, "apiUrl")
93
- );
94
- const accessToken = requiredValue(
95
- config.accessToken ?? environment.MITRA_PLATFORM_ACCESS_TOKEN,
96
- "accessToken"
97
- );
98
- const appId = requiredValue(config.appId ?? environment.MITRA_APP_ID, "appId");
99
- const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
100
- const fetchImplementation = config.fetch ?? globalThis.fetch;
101
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
102
- throw new MitraConfigurationError("timeoutMs must be a positive number");
103
- }
104
- if (typeof fetchImplementation !== "function") {
105
- throw new MitraConfigurationError("A fetch implementation is required");
106
- }
107
- const dataSourceId = config.dataSourceId ?? environment.MITRA_DATA_SOURCE_ID;
108
- if (dataSourceId !== void 0 && !dataSourceId.trim()) {
109
- throw new MitraConfigurationError("dataSourceId must not be empty when provided");
110
- }
111
- return {
112
- apiUrl,
113
- accessToken,
114
- appId,
115
- ...dataSourceId === void 0 ? {} : { dataSourceId: dataSourceId.trim() },
116
- timeoutMs,
117
- fetch: fetchImplementation
118
- };
119
- }
120
-
121
132
  // src/http-client.ts
122
133
  var bearerCredentialPattern = /(\bBearer\s+)\S+/gi;
123
134
  function redactText(value, accessToken) {
124
- return value.replace(bearerCredentialPattern, "$1[REDACTED]").split(accessToken).join("[REDACTED]");
135
+ const bearerRedacted = value.replace(bearerCredentialPattern, "$1[REDACTED]");
136
+ return accessToken ? bearerRedacted.split(accessToken).join("[REDACTED]") : bearerRedacted;
125
137
  }
126
138
  function redactDetails(value, accessToken) {
127
139
  if (typeof value === "string") return redactText(value, accessToken);
@@ -145,11 +157,31 @@ function optionalString(value) {
145
157
  function appendQueryParameters(url, params) {
146
158
  for (const [key, value] of Object.entries(params)) {
147
159
  if (value === void 0) continue;
148
- url.searchParams.append(key, typeof value === "string" ? value : value.toString());
160
+ const values = Array.isArray(value) ? value : [value];
161
+ for (const item of values) {
162
+ url.searchParams.append(key, typeof item === "string" ? item : item.toString());
163
+ }
149
164
  }
150
165
  }
166
+ function createRequestHeaders(hasBody, customHeaders, authentication) {
167
+ const safeCustomHeaders = Object.fromEntries(
168
+ Object.entries(customHeaders ?? {}).filter(
169
+ ([name]) => !["authorization", "x-app-id"].includes(name.toLowerCase())
170
+ )
171
+ );
172
+ return {
173
+ Accept: "application/json",
174
+ ...hasBody ? { "Content-Type": "application/json" } : {},
175
+ ...safeCustomHeaders,
176
+ ...authentication.type === "bearer" ? {
177
+ Authorization: `Bearer ${authentication.accessToken}`,
178
+ "X-App-Id": authentication.appId
179
+ } : {}
180
+ };
181
+ }
151
182
  async function parsePayload(response) {
152
183
  const text = await response.text();
184
+ if (response.ok && !text.trim()) return void 0;
153
185
  try {
154
186
  return JSON.parse(text);
155
187
  } catch {
@@ -182,6 +214,7 @@ function createApiError(response, payload, accessToken) {
182
214
  });
183
215
  }
184
216
  var HttpClient = class {
217
+ #authentication;
185
218
  #accessToken;
186
219
  baseUrl;
187
220
  appId;
@@ -189,30 +222,30 @@ var HttpClient = class {
189
222
  fetchImplementation;
190
223
  constructor(config) {
191
224
  this.baseUrl = config.baseUrl;
192
- this.#accessToken = config.accessToken;
193
- this.appId = config.appId;
225
+ this.#authentication = config.authentication;
226
+ this.#accessToken = config.authentication === "bearer" ? config.accessToken : void 0;
227
+ this.appId = config.authentication === "bearer" ? config.appId : void 0;
194
228
  this.timeoutMs = config.timeoutMs;
195
229
  this.fetchImplementation = config.fetch;
196
230
  }
197
231
  async request(path, options = {}) {
198
232
  const url = new URL(`${this.baseUrl}${path}`);
199
233
  appendQueryParameters(url, options.params ?? {});
200
- const controller = new AbortController();
201
- const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
234
+ const controller = this.timeoutMs === void 0 ? void 0 : new AbortController();
235
+ const timeout = controller === void 0 ? void 0 : setTimeout(() => controller.abort(), this.timeoutMs);
202
236
  const hasBody = options.body !== void 0;
237
+ const authentication = this.#authentication === "bearer" ? {
238
+ type: "bearer",
239
+ accessToken: this.#accessToken,
240
+ appId: this.appId
241
+ } : { type: "anonymous" };
203
242
  try {
204
243
  const response = await this.fetchImplementation(url, {
205
244
  method: options.method ?? "GET",
206
- headers: {
207
- Accept: "application/json",
208
- ...hasBody ? { "Content-Type": "application/json" } : {},
209
- Authorization: `Bearer ${this.#accessToken}`,
210
- "X-App-Id": this.appId,
211
- ...options.headers
212
- },
245
+ headers: createRequestHeaders(hasBody, options.headers, authentication),
213
246
  ...hasBody ? { body: JSON.stringify(options.body) } : {},
214
247
  redirect: "manual",
215
- signal: controller.signal
248
+ ...controller === void 0 ? {} : { signal: controller.signal }
216
249
  });
217
250
  if (response.status === 204) return void 0;
218
251
  const payload = await parsePayload(response);
@@ -220,7 +253,7 @@ var HttpClient = class {
220
253
  return payload;
221
254
  } catch (error) {
222
255
  if (error instanceof MitraApiError) throw error;
223
- if (controller.signal.aborted) {
256
+ if (controller?.signal.aborted) {
224
257
  throw new MitraApiError("Mitra request timed out", 0, {
225
258
  code: "REQUEST_TIMEOUT",
226
259
  retryable: true
@@ -231,7 +264,7 @@ var HttpClient = class {
231
264
  retryable: true
232
265
  });
233
266
  } finally {
234
- clearTimeout(timeout);
267
+ if (timeout !== void 0) clearTimeout(timeout);
235
268
  }
236
269
  }
237
270
  get(path, params) {
@@ -255,17 +288,385 @@ var HttpClient = class {
255
288
  }
256
289
  };
257
290
 
291
+ // src/agent-task-sse.ts
292
+ function invalidResponse(message) {
293
+ return new MitraApiError(message, 200, {
294
+ code: "INVALID_RESPONSE",
295
+ retryable: false
296
+ });
297
+ }
298
+ function parseAgentTaskEvent(data) {
299
+ let value;
300
+ try {
301
+ value = JSON.parse(data);
302
+ } catch {
303
+ throw invalidResponse("The Agent event stream returned invalid JSON");
304
+ }
305
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
306
+ throw invalidResponse("The Agent event stream returned an invalid event");
307
+ }
308
+ const event = value;
309
+ if (typeof event.type !== "string" || typeof event.timestamp !== "number") {
310
+ throw invalidResponse("The Agent event stream returned an invalid event");
311
+ }
312
+ if (event.sequence !== void 0 && typeof event.sequence !== "number") {
313
+ throw invalidResponse("The Agent event stream returned an invalid event sequence");
314
+ }
315
+ return value;
316
+ }
317
+ function consumeEventBlock(block, observer) {
318
+ let eventName = "message";
319
+ const data = [];
320
+ for (const rawLine of block.split(/\r?\n/)) {
321
+ const line = rawLine.replace(/^\uFEFF/, "");
322
+ if (!line || line.startsWith(":")) continue;
323
+ const separator = line.indexOf(":");
324
+ const field = separator === -1 ? line : line.slice(0, separator);
325
+ let value = separator === -1 ? "" : line.slice(separator + 1);
326
+ if (value.startsWith(" ")) value = value.slice(1);
327
+ if (field === "event") eventName = value;
328
+ if (field === "data") data.push(value);
329
+ }
330
+ if (eventName === "hello" || eventName === "ping") return;
331
+ if (eventName !== "message" || data.length === 0) return;
332
+ observer.onEvent(parseAgentTaskEvent(data.join("\n")));
333
+ }
334
+ async function readErrorPayload(response) {
335
+ const text = await response.text();
336
+ try {
337
+ return JSON.parse(text);
338
+ } catch {
339
+ return {};
340
+ }
341
+ }
342
+ var AgentTaskSseEventSource = class {
343
+ constructor(config) {
344
+ this.config = config;
345
+ }
346
+ async open(taskId, observer, signal, transport) {
347
+ if (transport === "websocket") {
348
+ throw new MitraConfigurationError(
349
+ "WebSocket Agent sessions are not available in the Functions runtime"
350
+ );
351
+ }
352
+ if (signal?.aborted) throw signal.reason ?? new Error("Agent event stream was aborted");
353
+ const controller = new AbortController();
354
+ let handshakeTimedOut = false;
355
+ let intentionallyClosed = false;
356
+ let disconnected = false;
357
+ const abortFromCaller = () => controller.abort(signal?.reason);
358
+ signal?.addEventListener("abort", abortFromCaller, { once: true });
359
+ const handshakeTimeout = this.config.timeoutMs === void 0 ? void 0 : setTimeout(() => {
360
+ handshakeTimedOut = true;
361
+ controller.abort();
362
+ }, this.config.timeoutMs);
363
+ const disconnect = (error) => {
364
+ if (disconnected || intentionallyClosed) return;
365
+ disconnected = true;
366
+ observer.onDisconnect(error);
367
+ };
368
+ const cleanup = () => signal?.removeEventListener("abort", abortFromCaller);
369
+ let response;
370
+ try {
371
+ const path = (0, import_sdk_core.encodePathSegment)(taskId, "taskId", this.config.errors);
372
+ response = await this.config.fetch(`${this.config.baseUrl}/api/v1/tasks/${path}/events`, {
373
+ method: "GET",
374
+ headers: {
375
+ Accept: "text/event-stream",
376
+ Authorization: `Bearer ${this.config.accessToken}`,
377
+ "X-App-Id": this.config.appId
378
+ },
379
+ redirect: "manual",
380
+ signal: controller.signal
381
+ });
382
+ } catch {
383
+ if (handshakeTimeout !== void 0) clearTimeout(handshakeTimeout);
384
+ cleanup();
385
+ if (handshakeTimedOut) {
386
+ throw new MitraApiError("Mitra Agent event stream handshake timed out", 0, {
387
+ code: "REQUEST_TIMEOUT",
388
+ retryable: true
389
+ });
390
+ }
391
+ if (signal?.aborted) throw signal.reason ?? new Error("Agent event stream was aborted");
392
+ throw new MitraApiError("The Mitra Agent event stream request failed", 0, {
393
+ code: "NETWORK_ERROR",
394
+ retryable: true
395
+ });
396
+ }
397
+ if (handshakeTimeout !== void 0) clearTimeout(handshakeTimeout);
398
+ if (!response.ok) {
399
+ cleanup();
400
+ throw createApiError(response, await readErrorPayload(response), this.config.accessToken);
401
+ }
402
+ if (!response.body) {
403
+ cleanup();
404
+ throw invalidResponse("The Agent event stream response has no body");
405
+ }
406
+ const contentType = response.headers.get("Content-Type") ?? "";
407
+ if (!contentType.toLowerCase().includes("text/event-stream")) {
408
+ controller.abort();
409
+ cleanup();
410
+ throw invalidResponse("The Agent event stream returned an invalid content type");
411
+ }
412
+ const reader = response.body.getReader();
413
+ const decoder = new TextDecoder();
414
+ let buffer = "";
415
+ void (async () => {
416
+ try {
417
+ while (true) {
418
+ const { done, value } = await reader.read();
419
+ if (done) break;
420
+ buffer += decoder.decode(value, { stream: true });
421
+ let boundary = /\r?\n\r?\n/.exec(buffer);
422
+ while (boundary?.index !== void 0) {
423
+ consumeEventBlock(buffer.slice(0, boundary.index), observer);
424
+ buffer = buffer.slice(boundary.index + boundary[0].length);
425
+ boundary = /\r?\n\r?\n/.exec(buffer);
426
+ }
427
+ }
428
+ buffer += decoder.decode();
429
+ if (buffer.trim()) consumeEventBlock(buffer, observer);
430
+ disconnect();
431
+ } catch (error) {
432
+ if (!controller.signal.aborted) {
433
+ controller.abort();
434
+ await reader.cancel().catch(() => void 0);
435
+ disconnect(error);
436
+ }
437
+ } finally {
438
+ cleanup();
439
+ reader.releaseLock();
440
+ }
441
+ })();
442
+ return {
443
+ close() {
444
+ if (intentionallyClosed) return;
445
+ intentionallyClosed = true;
446
+ cleanup();
447
+ controller.abort();
448
+ void reader.cancel().catch(() => void 0);
449
+ }
450
+ };
451
+ }
452
+ };
453
+
454
+ // src/app-scoped-apps.ts
455
+ function unavailable(operation) {
456
+ throw new MitraConfigurationError(
457
+ `apps.${operation} is not available in an app-scoped Functions runtime`
458
+ );
459
+ }
460
+ function assertCurrentApp(configuredAppId, requestedAppId) {
461
+ if (requestedAppId !== configuredAppId) {
462
+ throw new MitraConfigurationError(
463
+ `Code Studio access is fixed to app ${configuredAppId}; received ${requestedAppId}`
464
+ );
465
+ }
466
+ }
467
+ function createAppScopedAppsModule(apps, appId) {
468
+ const scoped = {
469
+ async list() {
470
+ return unavailable("list");
471
+ },
472
+ async get(requestedAppId, options) {
473
+ assertCurrentApp(appId, requestedAppId);
474
+ return apps.get(appId, options);
475
+ },
476
+ async create() {
477
+ return unavailable("create");
478
+ },
479
+ async delete(requestedAppId) {
480
+ assertCurrentApp(appId, requestedAppId);
481
+ return apps.delete(appId);
482
+ },
483
+ async update(requestedAppId, input) {
484
+ assertCurrentApp(appId, requestedAppId);
485
+ return apps.update(appId, input);
486
+ },
487
+ async getFiles(requestedAppId) {
488
+ assertCurrentApp(appId, requestedAppId);
489
+ return apps.getFiles(appId);
490
+ },
491
+ async replaceFiles(requestedAppId, files) {
492
+ assertCurrentApp(appId, requestedAppId);
493
+ return apps.replaceFiles(appId, files);
494
+ },
495
+ async mergeFiles(requestedAppId, files) {
496
+ assertCurrentApp(appId, requestedAppId);
497
+ return apps.mergeFiles(appId, files);
498
+ },
499
+ async build(requestedAppId) {
500
+ assertCurrentApp(appId, requestedAppId);
501
+ return apps.build(appId);
502
+ },
503
+ async publish(requestedAppId, options) {
504
+ assertCurrentApp(appId, requestedAppId);
505
+ return apps.publish(appId, options);
506
+ },
507
+ async getDeploy(requestedAppId, deployId) {
508
+ assertCurrentApp(appId, requestedAppId);
509
+ return apps.getDeploy(appId, deployId);
510
+ },
511
+ async getCurrentDeploy(requestedAppId) {
512
+ assertCurrentApp(appId, requestedAppId);
513
+ return apps.getCurrentDeploy(appId);
514
+ },
515
+ async cancelBuild(requestedAppId, deployId) {
516
+ assertCurrentApp(appId, requestedAppId);
517
+ return apps.cancelBuild(appId, deployId);
518
+ },
519
+ async rollback(requestedAppId, targetVersionId) {
520
+ assertCurrentApp(appId, requestedAppId);
521
+ return apps.rollback(appId, targetVersionId);
522
+ },
523
+ async listDeploys(requestedAppId, options) {
524
+ assertCurrentApp(appId, requestedAppId);
525
+ return apps.listDeploys(appId, options);
526
+ },
527
+ async listVersions(requestedAppId, options) {
528
+ assertCurrentApp(appId, requestedAppId);
529
+ return apps.listVersions(appId, options);
530
+ }
531
+ };
532
+ return {
533
+ apps: scoped,
534
+ currentApp: {
535
+ get: (options) => scoped.get(appId, options),
536
+ delete: () => scoped.delete(appId),
537
+ update: (input) => scoped.update(appId, input),
538
+ getFiles: () => scoped.getFiles(appId),
539
+ replaceFiles: (files) => scoped.replaceFiles(appId, files),
540
+ mergeFiles: (files) => scoped.mergeFiles(appId, files),
541
+ build: () => scoped.build(appId),
542
+ publish: (options) => scoped.publish(appId, options),
543
+ getDeploy: (deployId) => scoped.getDeploy(appId, deployId),
544
+ getCurrentDeploy: () => scoped.getCurrentDeploy(appId),
545
+ cancelBuild: (deployId) => scoped.cancelBuild(appId, deployId),
546
+ rollback: (targetVersionId) => scoped.rollback(appId, targetVersionId),
547
+ listDeploys: (options) => scoped.listDeploys(appId, options),
548
+ listVersions: (options) => scoped.listVersions(appId, options)
549
+ }
550
+ };
551
+ }
552
+
553
+ // src/config.ts
554
+ function readDefaultEnvironment() {
555
+ return typeof process === "undefined" ? {} : process.env;
556
+ }
557
+ function requiredValue(value, name) {
558
+ if (!value?.trim()) {
559
+ throw new MitraConfigurationError(`${name} is required`);
560
+ }
561
+ return value.trim();
562
+ }
563
+ function removeTrailingSlashes(value) {
564
+ let end = value.length;
565
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
566
+ return value.slice(0, end);
567
+ }
568
+ function normalizeApiUrl(value) {
569
+ let parsed;
570
+ try {
571
+ parsed = new URL(value);
572
+ } catch {
573
+ throw new MitraConfigurationError("apiUrl must be a valid HTTP or HTTPS URL");
574
+ }
575
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
576
+ throw new MitraConfigurationError("apiUrl must be a valid HTTP or HTTPS URL");
577
+ }
578
+ if (parsed.username || parsed.password || parsed.search || parsed.hash || value.includes("?") || value.includes("#")) {
579
+ throw new MitraConfigurationError(
580
+ "apiUrl must not include credentials, query parameters, or a fragment"
581
+ );
582
+ }
583
+ return removeTrailingSlashes(parsed.toString());
584
+ }
585
+ function deriveNativeApiUrl(legacyBaseUrl) {
586
+ if (legacyBaseUrl === void 0) return void 0;
587
+ const parsed = new URL(normalizeApiUrl(legacyBaseUrl));
588
+ parsed.pathname = parsed.pathname.replace(/\/legacy\/?$/, "") || "/";
589
+ return removeTrailingSlashes(parsed.toString());
590
+ }
591
+ function resolveConfig(config = {}, environment = readDefaultEnvironment()) {
592
+ const apiUrl = normalizeApiUrl(
593
+ requiredValue(
594
+ config.apiUrl ?? environment.MITRA_API_URL ?? deriveNativeApiUrl(environment.MITRA_BASE_URL),
595
+ "apiUrl"
596
+ )
597
+ );
598
+ const accessToken = requiredValue(
599
+ config.accessToken ?? environment.MITRA_PLATFORM_ACCESS_TOKEN ?? environment.MITRA_TOKEN,
600
+ "accessToken"
601
+ );
602
+ const appId = requiredValue(
603
+ config.appId ?? environment.MITRA_APP_ID ?? environment.MITRA_PROJECT_ID,
604
+ "appId"
605
+ );
606
+ const timeoutMs = config.timeoutMs;
607
+ const fetchImplementation = config.fetch ?? globalThis.fetch;
608
+ if (timeoutMs !== void 0 && (!Number.isFinite(timeoutMs) || timeoutMs <= 0)) {
609
+ throw new MitraConfigurationError("timeoutMs must be a positive number");
610
+ }
611
+ if (typeof fetchImplementation !== "function") {
612
+ throw new MitraConfigurationError("A fetch implementation is required");
613
+ }
614
+ const dataSourceId = config.dataSourceId ?? environment.MITRA_DATA_SOURCE_ID;
615
+ if (dataSourceId !== void 0 && !dataSourceId.trim()) {
616
+ throw new MitraConfigurationError("dataSourceId must not be empty when provided");
617
+ }
618
+ return {
619
+ apiUrl,
620
+ legacyBaseUrl: normalizeApiUrl(config.legacyBaseUrl ?? environment.MITRA_BASE_URL ?? apiUrl),
621
+ accessToken,
622
+ appId,
623
+ ...dataSourceId === void 0 ? {} : { dataSourceId: dataSourceId.trim() },
624
+ ...timeoutMs === void 0 ? {} : { timeoutMs },
625
+ fetch: fetchImplementation
626
+ };
627
+ }
628
+
629
+ // src/legacy/configure.ts
630
+ var import_mitra_sdk = require("mitra-sdk");
631
+ function configureLegacySdk(config) {
632
+ (0, import_mitra_sdk.configureSdkMitra)({
633
+ baseURL: config.legacyBaseUrl,
634
+ token: config.accessToken,
635
+ projectId: config.appId
636
+ });
637
+ }
638
+
258
639
  // src/client.ts
259
640
  var coreErrors = {
260
641
  configuration: (message) => new MitraConfigurationError(message),
261
642
  invalidResponse: (message) => new MitraApiError(message, 200, { code: "INVALID_RESPONSE", retryable: false })
262
643
  };
263
644
  var DefaultMitraClient = class {
645
+ agentConnections;
646
+ agentCredentials;
647
+ agents;
648
+ agentTasks;
649
+ apps;
264
650
  auth;
651
+ context;
652
+ currentApp;
653
+ customQueries;
654
+ dataSources;
265
655
  entities;
266
656
  functions;
657
+ functionsAdmin;
658
+ imports;
267
659
  integration;
660
+ integrationAdmin;
661
+ integrationResources;
662
+ integrationTemplates;
663
+ members;
664
+ messenger;
665
+ publicFunctions;
268
666
  queries;
667
+ schema;
668
+ sql;
669
+ workflows;
269
670
  #dataSourceId;
270
671
  #initPromise;
271
672
  #appId;
@@ -275,27 +676,78 @@ var DefaultMitraClient = class {
275
676
  this.#dataSourceId = config.dataSourceId;
276
677
  const httpClient = (service) => new HttpClient({
277
678
  baseUrl: `${config.apiUrl}/${service}`,
679
+ authentication: "bearer",
278
680
  accessToken: config.accessToken,
279
681
  appId: config.appId,
280
- timeoutMs: config.timeoutMs,
682
+ ...config.timeoutMs === void 0 ? {} : { timeoutMs: config.timeoutMs },
281
683
  fetch: config.fetch
282
684
  });
283
- const core = (0, import_sdk_core.createSdkCore)({
685
+ const core = (0, import_sdk_core2.createSdkCore)({
284
686
  transports: {
285
687
  auth: httpClient("iam"),
688
+ codeStudio: httpClient("code-studio"),
689
+ copilot: httpClient("copilot"),
286
690
  dataManager: httpClient("data-manager"),
287
691
  functions: httpClient("functions"),
288
- integration: httpClient("integration")
692
+ integration: httpClient("integration"),
693
+ messenger: httpClient("messenger"),
694
+ publicFunctions: new HttpClient({
695
+ baseUrl: `${config.apiUrl}/functions`,
696
+ authentication: "anonymous",
697
+ ...config.timeoutMs === void 0 ? {} : { timeoutMs: config.timeoutMs },
698
+ fetch: config.fetch
699
+ })
289
700
  },
290
- getDataSourceId: () => this.#dataSourceId,
701
+ getAppId: () => this.#appId,
291
702
  functions: { executeInvocationType: "sync", emptyInput: "empty-object" },
292
703
  errors: coreErrors
293
704
  });
705
+ const appModules = createAppScopedAppsModule(core.apps, this.#appId);
706
+ this.agentConnections = core.agentConnections;
707
+ this.agentCredentials = core.agentCredentials;
708
+ this.agents = core.agents;
709
+ const agentSessionManager = (0, import_sdk_core2.createAgentTaskSessionManager)({
710
+ tasks: core.agentTasks,
711
+ eventSource: new AgentTaskSseEventSource({
712
+ baseUrl: `${config.apiUrl}/copilot`,
713
+ accessToken: config.accessToken,
714
+ appId: config.appId,
715
+ ...config.timeoutMs === void 0 ? {} : { timeoutMs: config.timeoutMs },
716
+ fetch: config.fetch,
717
+ errors: coreErrors
718
+ })
719
+ });
720
+ this.agentTasks = (0, import_sdk_core2.withAgentTaskSessions)(core.agentTasks, {
721
+ session: (options) => {
722
+ if (options.transport === "websocket") {
723
+ throw new MitraConfigurationError(
724
+ "WebSocket Agent sessions are not available in the Functions runtime; use http or auto"
725
+ );
726
+ }
727
+ return agentSessionManager.session(options);
728
+ }
729
+ });
730
+ this.apps = appModules.apps;
294
731
  this.auth = core.auth;
732
+ this.context = core.context;
733
+ this.currentApp = appModules.currentApp;
734
+ this.customQueries = core.customQueries;
735
+ this.dataSources = core.dataSources;
295
736
  this.entities = core.entities;
296
737
  this.functions = core.functions;
738
+ this.functionsAdmin = core.functionsAdmin;
739
+ this.imports = core.imports;
297
740
  this.integration = core.integration;
741
+ this.integrationAdmin = core.integrationAdmin;
742
+ this.integrationResources = core.integrationResources;
743
+ this.integrationTemplates = core.integrationTemplates;
744
+ this.members = core.members;
745
+ this.messenger = core.messenger;
746
+ this.publicFunctions = core.publicFunctions;
298
747
  this.queries = core.queries;
748
+ this.schema = core.schema;
749
+ this.sql = core.sql;
750
+ this.workflows = core.workflows;
299
751
  this.#codeStudioHttpClient = httpClient("code-studio");
300
752
  }
301
753
  init() {
@@ -309,14 +761,15 @@ var DefaultMitraClient = class {
309
761
  return this.#initPromise;
310
762
  }
311
763
  async resolveDataSourceId() {
312
- const appInfo = (0, import_sdk_core.expectObject)(
764
+ const appInfo = (0, import_sdk_core2.expectObject)(
313
765
  await this.#codeStudioHttpClient.get(
314
- `/api/v1/apps/${(0, import_sdk_core.encodePathSegment)(this.#appId, "appId", coreErrors)}/info`
766
+ `/api/v1/apps/${(0, import_sdk_core2.encodePathSegment)(this.#appId, "appId", coreErrors)}/info`
315
767
  ),
316
768
  "App info response",
317
769
  coreErrors
318
770
  );
319
- if (!appInfo.dataSourceId?.trim()) {
771
+ if (appInfo.dataSourceId === null) return;
772
+ if (typeof appInfo.dataSourceId !== "string" || !appInfo.dataSourceId.trim()) {
320
773
  throw new MitraApiError("The app info response does not include a dataSourceId", 200, {
321
774
  code: "INVALID_RESPONSE",
322
775
  retryable: false
@@ -325,16 +778,149 @@ var DefaultMitraClient = class {
325
778
  this.#dataSourceId = appInfo.dataSourceId;
326
779
  }
327
780
  };
781
+ function createConfiguredClient(config) {
782
+ configureLegacySdk(config);
783
+ return new DefaultMitraClient(config);
784
+ }
328
785
  function createClient(config = {}) {
329
- return new DefaultMitraClient(resolveConfig(config));
786
+ return createConfiguredClient(resolveConfig(config));
330
787
  }
331
788
  function createClientFromEnvironment(environment) {
332
- return new DefaultMitraClient(resolveConfig({}, environment));
789
+ return createConfiguredClient(resolveConfig({}, environment));
333
790
  }
791
+
792
+ // src/index.ts
793
+ var import_sdk_core3 = require("@mitralab.io/sdk-core");
794
+
795
+ // src/legacy/index.ts
796
+ var legacy = __toESM(require("mitra-sdk"), 1);
797
+ var configureSdkMitra3 = legacy.configureSdkMitra;
798
+ var createMitraSdkInstance2 = legacy.createMitraSdkInstance;
799
+ var resolveProjectId2 = legacy.resolveProjectId;
800
+ var createRecordMitra2 = legacy.createRecordMitra;
801
+ var createRecordsBatchMitra2 = legacy.createRecordsBatchMitra;
802
+ var getRecordMitra2 = legacy.getRecordMitra;
803
+ var listRecordsMitra2 = legacy.listRecordsMitra;
804
+ var updateRecordMitra2 = legacy.updateRecordMitra;
805
+ var patchRecordMitra2 = legacy.patchRecordMitra;
806
+ var deleteRecordMitra2 = legacy.deleteRecordMitra;
807
+ var executeServerFunctionMitra2 = legacy.executeServerFunctionMitra;
808
+ var executeServerFunctionAsyncMitra2 = legacy.executeServerFunctionAsyncMitra;
809
+ var getServerFunctionExecutionMitra2 = legacy.getServerFunctionExecutionMitra;
810
+ var stopServerFunctionExecutionMitra2 = legacy.stopServerFunctionExecutionMitra;
811
+ var executePublicServerFunctionAsyncMitra2 = legacy.executePublicServerFunctionAsyncMitra;
812
+ var callIntegrationMitra2 = legacy.callIntegrationMitra;
813
+ var listIntegrationsMitra2 = legacy.listIntegrationsMitra;
814
+ var getProjectsMitra2 = legacy.getProjectsMitra;
815
+ var getProjectContextMitra2 = legacy.getProjectContextMitra;
816
+ var listProjectsMitra2 = legacy.listProjectsMitra;
817
+ var createProjectMitra2 = legacy.createProjectMitra;
818
+ var updateProjectSettingsMitra2 = legacy.updateProjectSettingsMitra;
819
+ var getGitConfigMitra2 = legacy.getGitConfigMitra;
820
+ var createJdbcConnectionMitra2 = legacy.createJdbcConnectionMitra;
821
+ var listJdbcConnectionsMitra2 = legacy.listJdbcConnectionsMitra;
822
+ var updateJdbcConnectionMitra2 = legacy.updateJdbcConnectionMitra;
823
+ var deleteJdbcConnectionMitra2 = legacy.deleteJdbcConnectionMitra;
824
+ var runQueryMitra2 = legacy.runQueryMitra;
825
+ var runDdlMitra2 = legacy.runDdlMitra;
826
+ var runDmlMitra2 = legacy.runDmlMitra;
827
+ var listTablesMitra2 = legacy.listTablesMitra;
828
+ var createOnlineTableMitra2 = legacy.createOnlineTableMitra;
829
+ var listOnlineTablesMitra2 = legacy.listOnlineTablesMitra;
830
+ var updateOnlineTableMitra2 = legacy.updateOnlineTableMitra;
831
+ var deleteOnlineTableMitra2 = legacy.deleteOnlineTableMitra;
832
+ var createServerFunctionMitra2 = legacy.createServerFunctionMitra;
833
+ var readServerFunctionMitra2 = legacy.readServerFunctionMitra;
834
+ var listServerFunctionsMitra2 = legacy.listServerFunctionsMitra;
835
+ var updateServerFunctionMitra2 = legacy.updateServerFunctionMitra;
836
+ var deleteServerFunctionMitra2 = legacy.deleteServerFunctionMitra;
837
+ var togglePublicExecutionMitra2 = legacy.togglePublicExecutionMitra;
838
+ var createIntegrationMitra2 = legacy.createIntegrationMitra;
839
+ var updateIntegrationMitra2 = legacy.updateIntegrationMitra;
840
+ var deleteIntegrationMitra2 = legacy.deleteIntegrationMitra;
841
+ var testIntegrationMitra2 = legacy.testIntegrationMitra;
842
+ var testIntegrationByIdMitra2 = legacy.testIntegrationByIdMitra;
843
+ var listIntegrationTemplatesMitra2 = legacy.listIntegrationTemplatesMitra;
844
+ var getIntegrationTemplateMitra2 = legacy.getIntegrationTemplateMitra;
845
+ var createAgentMitra2 = legacy.createAgentMitra;
846
+ var readAgentMitra2 = legacy.readAgentMitra;
847
+ var listAgentsMitra2 = legacy.listAgentsMitra;
848
+ var updateAgentMitra2 = legacy.updateAgentMitra;
849
+ var deleteAgentMitra2 = legacy.deleteAgentMitra;
850
+ var getAgentTaskMitra2 = legacy.getAgentTaskMitra;
851
+ var manageAgentChatMitra2 = legacy.manageAgentChatMitra;
852
+ var manageAgentCredentialMitra2 = legacy.manageAgentCredentialMitra;
853
+ var manageAgentConnectionMitra2 = legacy.manageAgentConnectionMitra;
854
+ var inviteUserMitra2 = legacy.inviteUserMitra;
855
+ var unsubscribeUserMitra2 = legacy.unsubscribeUserMitra;
856
+ var deployToS3Mitra2 = legacy.deployToS3Mitra;
857
+ var getDeployStatusMitra2 = legacy.getDeployStatusMitra;
334
858
  // Annotate the CommonJS export names for ESM import in node:
335
859
  0 && (module.exports = {
860
+ AgentTaskTurnError,
336
861
  MitraApiError,
337
862
  MitraConfigurationError,
863
+ callIntegrationMitra,
864
+ configureSdkMitra,
865
+ createAgentMitra,
338
866
  createClient,
339
- createClientFromEnvironment
867
+ createClientFromEnvironment,
868
+ createIntegrationMitra,
869
+ createJdbcConnectionMitra,
870
+ createMitraSdkInstance,
871
+ createOnlineTableMitra,
872
+ createProjectMitra,
873
+ createRecordMitra,
874
+ createRecordsBatchMitra,
875
+ createServerFunctionMitra,
876
+ deleteAgentMitra,
877
+ deleteIntegrationMitra,
878
+ deleteJdbcConnectionMitra,
879
+ deleteOnlineTableMitra,
880
+ deleteRecordMitra,
881
+ deleteServerFunctionMitra,
882
+ deployToS3Mitra,
883
+ executePublicServerFunctionAsyncMitra,
884
+ executeServerFunctionAsyncMitra,
885
+ executeServerFunctionMitra,
886
+ getAgentTaskMitra,
887
+ getDeployStatusMitra,
888
+ getGitConfigMitra,
889
+ getIntegrationTemplateMitra,
890
+ getProjectContextMitra,
891
+ getProjectsMitra,
892
+ getRecordMitra,
893
+ getServerFunctionExecutionMitra,
894
+ inviteUserMitra,
895
+ listAgentsMitra,
896
+ listIntegrationTemplatesMitra,
897
+ listIntegrationsMitra,
898
+ listJdbcConnectionsMitra,
899
+ listOnlineTablesMitra,
900
+ listProjectsMitra,
901
+ listRecordsMitra,
902
+ listServerFunctionsMitra,
903
+ listTablesMitra,
904
+ manageAgentChatMitra,
905
+ manageAgentConnectionMitra,
906
+ manageAgentCredentialMitra,
907
+ patchRecordMitra,
908
+ readAgentMitra,
909
+ readServerFunctionMitra,
910
+ resolveProjectId,
911
+ runDdlMitra,
912
+ runDmlMitra,
913
+ runQueryMitra,
914
+ stopServerFunctionExecutionMitra,
915
+ testIntegrationByIdMitra,
916
+ testIntegrationMitra,
917
+ togglePublicExecutionMitra,
918
+ unsubscribeUserMitra,
919
+ updateAgentMitra,
920
+ updateIntegrationMitra,
921
+ updateJdbcConnectionMitra,
922
+ updateOnlineTableMitra,
923
+ updateProjectSettingsMitra,
924
+ updateRecordMitra,
925
+ updateServerFunctionMitra
340
926
  });