@xylex-group/athena 2.9.0 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +112 -28
  2. package/dist/browser.cjs +865 -74
  3. package/dist/browser.cjs.map +1 -1
  4. package/dist/browser.d.cts +3 -3
  5. package/dist/browser.d.ts +3 -3
  6. package/dist/browser.js +862 -75
  7. package/dist/browser.js.map +1 -1
  8. package/dist/cli/index.cjs +785 -40
  9. package/dist/cli/index.cjs.map +1 -1
  10. package/dist/cli/index.js +785 -40
  11. package/dist/cli/index.js.map +1 -1
  12. package/dist/{client-D6EIJdQS.d.ts → client-DD_UeF3Q.d.ts} +508 -22
  13. package/dist/{client-CfAE_QOj.d.cts → client-WqBuu60O.d.cts} +508 -22
  14. package/dist/index.cjs +865 -74
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.cts +2 -2
  17. package/dist/index.d.ts +2 -2
  18. package/dist/index.js +862 -75
  19. package/dist/index.js.map +1 -1
  20. package/dist/{react-email-BvJ3fj_F.d.cts → module-BFMyVmwX.d.cts} +97 -2
  21. package/dist/{react-email-PLAJuZuO.d.ts → module-DRkIHtY-.d.ts} +97 -2
  22. package/dist/next/client.cjs +793 -40
  23. package/dist/next/client.cjs.map +1 -1
  24. package/dist/next/client.d.cts +3 -4
  25. package/dist/next/client.d.ts +3 -4
  26. package/dist/next/client.js +793 -40
  27. package/dist/next/client.js.map +1 -1
  28. package/dist/next/server.cjs +793 -40
  29. package/dist/next/server.cjs.map +1 -1
  30. package/dist/next/server.d.cts +2 -2
  31. package/dist/next/server.d.ts +2 -2
  32. package/dist/next/server.js +793 -40
  33. package/dist/next/server.js.map +1 -1
  34. package/dist/react.cjs +1 -1
  35. package/dist/react.cjs.map +1 -1
  36. package/dist/react.d.cts +2 -3
  37. package/dist/react.d.ts +2 -3
  38. package/dist/react.js +1 -1
  39. package/dist/react.js.map +1 -1
  40. package/dist/{shared-BW6hoLBY.d.cts → shared-B1ueL-Ox.d.cts} +3 -1
  41. package/dist/{shared-BiJvoURI.d.ts → shared-GPAprhBb.d.ts} +3 -1
  42. package/package.json +2 -2
@@ -136,8 +136,8 @@ function parseCookies(cookieHeader) {
136
136
  });
137
137
  return cookieMap;
138
138
  }
139
- var getSessionCookie = (request, config) => {
140
- const cookies = (request instanceof Headers || !("headers" in request) ? request : request.headers).get("cookie");
139
+ var getSessionCookie = (request2, config) => {
140
+ const cookies = (request2 instanceof Headers || !("headers" in request2) ? request2 : request2.headers).get("cookie");
141
141
  if (!cookies) {
142
142
  return null;
143
143
  }
@@ -160,7 +160,7 @@ var getSessionCookie = (request, config) => {
160
160
 
161
161
  // package.json
162
162
  var package_default = {
163
- version: "2.9.0"
163
+ version: "2.11.0"
164
164
  };
165
165
 
166
166
  // src/sdk-version.ts
@@ -1141,6 +1141,87 @@ function mergeCallOptions(base, override) {
1141
1141
  }
1142
1142
  };
1143
1143
  }
1144
+ function copyDefinedField(target, source, targetKey, sourceKey) {
1145
+ if (!(sourceKey in source)) {
1146
+ return;
1147
+ }
1148
+ const value = source[sourceKey];
1149
+ if (value !== void 0) {
1150
+ target[targetKey] = value;
1151
+ }
1152
+ }
1153
+ function normalizeEmailTemplateAttachmentsValue(value) {
1154
+ if (typeof value === "string" || value == null) {
1155
+ return value;
1156
+ }
1157
+ if (Array.isArray(value)) {
1158
+ return value.map((item) => normalizeEmailTemplateAttachmentsValue(item));
1159
+ }
1160
+ if (typeof value !== "object") {
1161
+ return value;
1162
+ }
1163
+ const attachment = { ...value };
1164
+ copyDefinedField(attachment, attachment, "file_url", "fileUrl");
1165
+ delete attachment.fileUrl;
1166
+ return attachment;
1167
+ }
1168
+ function normalizeAdminEmailTemplatePayload(payload) {
1169
+ const normalized = { ...payload };
1170
+ copyDefinedField(normalized, payload, "template_key", "templateKey");
1171
+ copyDefinedField(normalized, payload, "event_type", "eventType");
1172
+ copyDefinedField(normalized, payload, "subject_template", "subjectTemplate");
1173
+ copyDefinedField(normalized, payload, "text_template", "textTemplate");
1174
+ copyDefinedField(normalized, payload, "html_template", "htmlTemplate");
1175
+ copyDefinedField(normalized, payload, "variable_bindings", "variableBindings");
1176
+ copyDefinedField(normalized, payload, "attachment_failure_mode", "attachmentFailureMode");
1177
+ copyDefinedField(normalized, payload, "is_active", "isActive");
1178
+ if (Object.hasOwn(payload, "attachments")) {
1179
+ normalized.attachments = normalizeEmailTemplateAttachmentsValue(payload.attachments);
1180
+ }
1181
+ delete normalized.templateKey;
1182
+ delete normalized.eventType;
1183
+ delete normalized.subjectTemplate;
1184
+ delete normalized.textTemplate;
1185
+ delete normalized.htmlTemplate;
1186
+ delete normalized.variableBindings;
1187
+ delete normalized.attachmentFailureMode;
1188
+ delete normalized.isActive;
1189
+ return normalized;
1190
+ }
1191
+ function toReactEmailTemplateCompatibilityInput(input) {
1192
+ const payload = input;
1193
+ const compatibility = { ...payload };
1194
+ copyDefinedField(compatibility, payload, "templateKey", "template_key");
1195
+ copyDefinedField(compatibility, payload, "eventType", "event_type");
1196
+ copyDefinedField(compatibility, payload, "subjectTemplate", "subject_template");
1197
+ copyDefinedField(compatibility, payload, "textTemplate", "text_template");
1198
+ copyDefinedField(compatibility, payload, "htmlTemplate", "html_template");
1199
+ copyDefinedField(compatibility, payload, "variableBindings", "variable_bindings");
1200
+ copyDefinedField(compatibility, payload, "attachmentFailureMode", "attachment_failure_mode");
1201
+ copyDefinedField(compatibility, payload, "isActive", "is_active");
1202
+ return compatibility;
1203
+ }
1204
+ function normalizeAdminEmailTemplateSendPayload(payload) {
1205
+ const normalized = { ...payload };
1206
+ copyDefinedField(normalized, payload, "template_id", "templateId");
1207
+ copyDefinedField(normalized, payload, "recipient_email", "recipientEmail");
1208
+ copyDefinedField(normalized, payload, "render_variables", "renderVariables");
1209
+ copyDefinedField(normalized, payload, "user_id", "userId");
1210
+ copyDefinedField(normalized, payload, "organization_id", "organizationId");
1211
+ copyDefinedField(normalized, payload, "session_token", "sessionToken");
1212
+ copyDefinedField(normalized, payload, "attachment_failure_mode", "attachmentFailureMode");
1213
+ if (Object.hasOwn(payload, "attachments")) {
1214
+ normalized.attachments = normalizeEmailTemplateAttachmentsValue(payload.attachments);
1215
+ }
1216
+ delete normalized.templateId;
1217
+ delete normalized.recipientEmail;
1218
+ delete normalized.renderVariables;
1219
+ delete normalized.userId;
1220
+ delete normalized.organizationId;
1221
+ delete normalized.sessionToken;
1222
+ delete normalized.attachmentFailureMode;
1223
+ return normalized;
1224
+ }
1144
1225
  function toSessionGuardFailure(sessionResult) {
1145
1226
  if (sessionResult.status === 401 || sessionResult.data == null) {
1146
1227
  return {
@@ -1447,7 +1528,7 @@ function createAuthClient(config = {}) {
1447
1528
  ...config,
1448
1529
  baseUrl: normalizedBaseUrl
1449
1530
  };
1450
- const request = (input, options) => {
1531
+ const request2 = (input, options) => {
1451
1532
  const method = input.method ?? (input.body !== void 0 ? "POST" : inferDefaultMethod(input.endpoint));
1452
1533
  const mergedOptions = mergeCallOptions(input.fetchOptions, options);
1453
1534
  return callAuthEndpoint(
@@ -1460,7 +1541,7 @@ function createAuthClient(config = {}) {
1460
1541
  };
1461
1542
  const postGeneric = (endpoint, input, options) => {
1462
1543
  const { payload, fetchOptions } = extractFetchOptions(input);
1463
- return request(
1544
+ return request2(
1464
1545
  {
1465
1546
  endpoint,
1466
1547
  method: "POST",
@@ -1472,7 +1553,7 @@ function createAuthClient(config = {}) {
1472
1553
  };
1473
1554
  const getGeneric = (endpoint, input, options) => {
1474
1555
  const { fetchOptions } = extractFetchOptions(input);
1475
- return request(
1556
+ return request2(
1476
1557
  {
1477
1558
  endpoint,
1478
1559
  method: "GET",
@@ -1484,7 +1565,7 @@ function createAuthClient(config = {}) {
1484
1565
  const getWithQuery = (endpoint, input, options) => {
1485
1566
  const { payload, fetchOptions } = extractFetchOptions(input);
1486
1567
  const query = payload?.query;
1487
- return request(
1568
+ return request2(
1488
1569
  {
1489
1570
  endpoint,
1490
1571
  method: "GET",
@@ -1502,18 +1583,19 @@ function createAuthClient(config = {}) {
1502
1583
  htmlField: "htmlBody",
1503
1584
  textField: "textBody"
1504
1585
  }, withReactEmailRoute(route));
1505
- const resolveAdminEmailTemplatePayload = (route, input) => resolveReactEmailPayloadFields(input, {
1586
+ const resolveAdminEmailTemplatePayload = (route, input) => resolveReactEmailPayloadFields(toReactEmailTemplateCompatibilityInput(input), {
1506
1587
  htmlField: "htmlTemplate",
1507
1588
  textField: "textTemplate",
1508
1589
  variablesField: "variables"
1509
1590
  }, withReactEmailRoute(route)).then((payload) => {
1591
+ const normalizedPayload = normalizeAdminEmailTemplatePayload(payload);
1510
1592
  if ("variables" in payload && payload.variables !== void 0 && payload.variables !== null) {
1511
1593
  assertAthenaAuthTemplateVariables(
1512
1594
  payload.variables,
1513
1595
  `${route} variables`
1514
1596
  );
1515
1597
  }
1516
- return payload;
1598
+ return normalizedPayload;
1517
1599
  });
1518
1600
  const requireSession = async (input, options) => {
1519
1601
  const sessionInput = input?.fetchOptions ? { fetchOptions: input.fetchOptions } : void 0;
@@ -2089,7 +2171,15 @@ function createAuthClient(config = {}) {
2089
2171
  await resolveAdminEmailTemplatePayload("/admin/email-template/update", input),
2090
2172
  options
2091
2173
  ),
2092
- delete: (input, options) => postGeneric("/admin/email-template/delete", input, options)
2174
+ delete: (input, options) => postGeneric("/admin/email-template/delete", input, options),
2175
+ send: (input, options) => postGeneric(
2176
+ "/admin/email-template/send",
2177
+ normalizeAdminEmailTemplateSendPayload(extractFetchOptions(input).payload),
2178
+ options
2179
+ )
2180
+ },
2181
+ eventType: {
2182
+ list: (input, options) => getWithQuery("/admin/email-event-type/list", input, options)
2093
2183
  }
2094
2184
  },
2095
2185
  emailTemplate: {
@@ -2105,7 +2195,15 @@ function createAuthClient(config = {}) {
2105
2195
  "/admin/email-template/update",
2106
2196
  await resolveAdminEmailTemplatePayload("/admin/email-template/update", input),
2107
2197
  options
2198
+ ),
2199
+ send: (input, options) => postGeneric(
2200
+ "/admin/email-template/send",
2201
+ normalizeAdminEmailTemplateSendPayload(extractFetchOptions(input).payload),
2202
+ options
2108
2203
  )
2204
+ },
2205
+ emailEventType: {
2206
+ list: (input, options) => getWithQuery("/admin/email-event-type/list", input, options)
2109
2207
  }
2110
2208
  },
2111
2209
  apiKey: {
@@ -2145,7 +2243,7 @@ function createAuthClient(config = {}) {
2145
2243
  throw new Error("callback.provider requires non-empty code and state values");
2146
2244
  }
2147
2245
  const endpoint = `/callback/${encodeURIComponent(provider)}`;
2148
- return request({
2246
+ return request2({
2149
2247
  endpoint,
2150
2248
  method: "GET",
2151
2249
  query: {
@@ -2159,7 +2257,7 @@ function createAuthClient(config = {}) {
2159
2257
  };
2160
2258
  return {
2161
2259
  baseUrl: normalizedBaseUrl,
2162
- request,
2260
+ request: request2,
2163
2261
  signIn: {
2164
2262
  email: (input, options) => executePostWithCompatibleInput(
2165
2263
  resolvedConfig,
@@ -2697,16 +2795,16 @@ function createStorageFileModule(base, config = {}) {
2697
2795
  };
2698
2796
  });
2699
2797
  input.onProgress?.(createProgressSnapshot("preparing", sources, 0, 0, 0));
2700
- const uploadUrls = uploadRequests.length === 1 ? [await base.createStorageUploadUrl(uploadRequests[0].uploadRequest, options)] : (await base.createStorageUploadUrls({ files: uploadRequests.map((request) => request.uploadRequest) }, options)).files;
2798
+ const uploadUrls = uploadRequests.length === 1 ? [await base.createStorageUploadUrl(uploadRequests[0].uploadRequest, options)] : (await base.createStorageUploadUrls({ files: uploadRequests.map((request2) => request2.uploadRequest) }, options)).files;
2701
2799
  const aggregateLoaded = new Array(uploadRequests.length).fill(0);
2702
2800
  const uploaded = [];
2703
2801
  for (let index = 0; index < uploadRequests.length; index += 1) {
2704
- const request = uploadRequests[index];
2802
+ const request2 = uploadRequests[index];
2705
2803
  const uploadUrl = uploadUrls[index];
2706
2804
  const response = await putUploadBody(
2707
2805
  uploadUrl.upload.url,
2708
2806
  uploadUrl.upload.headers ?? {},
2709
- request.source,
2807
+ request2.source,
2710
2808
  input,
2711
2809
  options,
2712
2810
  (progress) => {
@@ -2717,13 +2815,13 @@ function createStorageFileModule(base, config = {}) {
2717
2815
  uploaded.push({
2718
2816
  file: uploadUrl.file,
2719
2817
  upload: uploadUrl.upload,
2720
- source: request.source.source,
2721
- fileName: request.source.fileName,
2722
- storage_key: request.uploadRequest.storage_key,
2818
+ source: request2.source.source,
2819
+ fileName: request2.source.fileName,
2820
+ storage_key: request2.uploadRequest.storage_key,
2723
2821
  response
2724
2822
  });
2725
- aggregateLoaded[index] = request.source.sizeBytes;
2726
- input.onProgress?.(createProgressSnapshot("complete", sources, index, request.source.sizeBytes, sum(aggregateLoaded)));
2823
+ aggregateLoaded[index] = request2.source.sizeBytes;
2824
+ input.onProgress?.(createProgressSnapshot("complete", sources, index, request2.source.sizeBytes, sum(aggregateLoaded)));
2727
2825
  }
2728
2826
  return {
2729
2827
  files: uploaded,
@@ -4684,6 +4782,484 @@ function createStorageModule(gateway, runtimeOptions) {
4684
4782
  };
4685
4783
  }
4686
4784
 
4785
+ // src/chat/module.ts
4786
+ var SDK_NAME3 = "xylex-group/athena-chat";
4787
+ var SDK_HEADER_VALUE3 = buildSdkHeaderValue(SDK_NAME3);
4788
+ var NO_CACHE_HEADER_VALUE3 = "no-cache";
4789
+ var AthenaChatError = class extends Error {
4790
+ status;
4791
+ endpoint;
4792
+ method;
4793
+ requestId;
4794
+ body;
4795
+ constructor(input) {
4796
+ super(input.message);
4797
+ this.name = "AthenaChatError";
4798
+ this.status = input.status;
4799
+ this.endpoint = input.endpoint;
4800
+ this.method = input.method;
4801
+ this.requestId = input.requestId;
4802
+ this.body = input.body;
4803
+ }
4804
+ };
4805
+ function deriveRealtimeInfoUrl(wsUrl) {
4806
+ if (!wsUrl) {
4807
+ return void 0;
4808
+ }
4809
+ const parsed = new URL(normalizeWsUrl(wsUrl, "Athena chat WebSocket URL"));
4810
+ parsed.protocol = parsed.protocol === "wss:" ? "https:" : "http:";
4811
+ parsed.pathname = parsed.pathname.replace(/\/wss\/gateway$/, "/wss/info");
4812
+ return parsed.toString();
4813
+ }
4814
+ function normalizeWsUrl(value, label) {
4815
+ const normalized = value.trim();
4816
+ if (!normalized) {
4817
+ throw new Error(`${label} is required.`);
4818
+ }
4819
+ let parsed;
4820
+ try {
4821
+ parsed = new URL(normalized);
4822
+ } catch {
4823
+ throw new Error(`${label} must be a valid absolute ws(s) URL.`);
4824
+ }
4825
+ if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") {
4826
+ throw new Error(`${label} must use ws or wss.`);
4827
+ }
4828
+ parsed.pathname = parsed.pathname.replace(/\/+$/, "");
4829
+ return parsed.toString().replace(/\/$/, "");
4830
+ }
4831
+ function isRecord7(value) {
4832
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
4833
+ }
4834
+ function normalizeHeaderValue3(value) {
4835
+ return value ? value : void 0;
4836
+ }
4837
+ function parseResponseBody4(rawText, contentType) {
4838
+ if (!rawText) {
4839
+ return { parsed: null, parseFailed: false };
4840
+ }
4841
+ const contentTypeSuggestsJson = contentType?.toLowerCase().includes("application/json") ?? false;
4842
+ const looksJson = contentTypeSuggestsJson || rawText.startsWith("{") || rawText.startsWith("[");
4843
+ if (!looksJson) {
4844
+ return { parsed: rawText, parseFailed: false };
4845
+ }
4846
+ try {
4847
+ return { parsed: JSON.parse(rawText), parseFailed: false };
4848
+ } catch {
4849
+ return { parsed: rawText, parseFailed: true };
4850
+ }
4851
+ }
4852
+ function resolveRequestId3(headers) {
4853
+ return headers.get("x-request-id") ?? headers.get("x-correlation-id") ?? headers.get("x-athena-request-id") ?? void 0;
4854
+ }
4855
+ function resolveErrorMessage4(payload, fallback) {
4856
+ if (isRecord7(payload)) {
4857
+ for (const candidate of [payload.error, payload.message, payload.details]) {
4858
+ if (typeof candidate === "string" && candidate.trim().length > 0) {
4859
+ return candidate.trim();
4860
+ }
4861
+ }
4862
+ }
4863
+ if (typeof payload === "string" && payload.trim().length > 0) {
4864
+ return payload.trim();
4865
+ }
4866
+ return fallback;
4867
+ }
4868
+ function encodePathSegment(value, label) {
4869
+ const normalized = value.trim();
4870
+ if (!normalized) {
4871
+ throw new Error(`${label} is required.`);
4872
+ }
4873
+ return encodeURIComponent(normalized);
4874
+ }
4875
+ function encodeQuery(query) {
4876
+ if (!query) {
4877
+ return "";
4878
+ }
4879
+ const params = new URLSearchParams();
4880
+ for (const [key, value] of Object.entries(query)) {
4881
+ if (value === void 0 || value === null) {
4882
+ continue;
4883
+ }
4884
+ if (Array.isArray(value)) {
4885
+ for (const item of value) {
4886
+ if (item !== void 0 && item !== null) {
4887
+ params.append(key, String(item));
4888
+ }
4889
+ }
4890
+ continue;
4891
+ }
4892
+ params.set(key, String(value));
4893
+ }
4894
+ const encoded = params.toString();
4895
+ return encoded ? `?${encoded}` : "";
4896
+ }
4897
+ function createSocket(factory, url, protocols) {
4898
+ try {
4899
+ return new factory(url, protocols);
4900
+ } catch (error) {
4901
+ if (error instanceof TypeError) {
4902
+ return factory(url, protocols);
4903
+ }
4904
+ throw error;
4905
+ }
4906
+ }
4907
+ function buildHeaders3(config, options) {
4908
+ const headers = {
4909
+ Accept: "application/json",
4910
+ apikey: config.apiKey,
4911
+ "x-api-key": config.apiKey,
4912
+ "X-Athena-Sdk": SDK_HEADER_VALUE3
4913
+ };
4914
+ if (config.client || options?.client) {
4915
+ headers["X-Athena-Client"] = options?.client ?? config.client ?? "";
4916
+ }
4917
+ const bearerToken = options?.bearerToken ?? config.bearerToken;
4918
+ if (typeof bearerToken === "string" && bearerToken.trim()) {
4919
+ headers.Authorization = bearerToken.startsWith("Bearer ") ? bearerToken : `Bearer ${bearerToken}`;
4920
+ }
4921
+ const cookie = options?.cookie ?? config.cookie;
4922
+ if (typeof cookie === "string" && cookie.trim()) {
4923
+ headers.Cookie = cookie;
4924
+ }
4925
+ const sessionToken = options?.sessionToken ?? config.sessionToken;
4926
+ if (typeof sessionToken === "string" && sessionToken.trim()) {
4927
+ headers["X-Athena-Auth-Session-Token"] = sessionToken;
4928
+ }
4929
+ if (config.forceNoCache || options?.forceNoCache) {
4930
+ headers["Cache-Control"] = NO_CACHE_HEADER_VALUE3;
4931
+ }
4932
+ for (const source of [config.headers, options?.headers]) {
4933
+ for (const [key, value] of Object.entries(source ?? {})) {
4934
+ const normalized = normalizeHeaderValue3(value);
4935
+ if (normalized) {
4936
+ headers[key] = normalized;
4937
+ }
4938
+ }
4939
+ }
4940
+ return headers;
4941
+ }
4942
+ function withJsonBody(init, body) {
4943
+ return {
4944
+ ...init,
4945
+ body: body === void 0 ? void 0 : JSON.stringify(body),
4946
+ headers: {
4947
+ "Content-Type": "application/json",
4948
+ ...init.headers
4949
+ }
4950
+ };
4951
+ }
4952
+ async function request(config, method, endpoint, options, body) {
4953
+ if (!config.baseUrl) {
4954
+ throw new Error(
4955
+ "Athena chat base URL is not configured. Pass createClient({ url }) for unified routing or set chat.url / chatUrl explicitly."
4956
+ );
4957
+ }
4958
+ const url = `${config.baseUrl}${endpoint}`;
4959
+ const init = {
4960
+ method,
4961
+ headers: buildHeaders3(config, options),
4962
+ signal: options?.signal
4963
+ };
4964
+ const finalInit = body === void 0 || method === "GET" ? init : withJsonBody(init, body);
4965
+ const response = await fetch(url, finalInit);
4966
+ const rawText = await response.text();
4967
+ const { parsed } = parseResponseBody4(rawText, response.headers.get("content-type"));
4968
+ if (!response.ok) {
4969
+ throw new AthenaChatError({
4970
+ message: resolveErrorMessage4(parsed, `Athena chat ${method} ${endpoint} failed with ${response.status}`),
4971
+ status: response.status,
4972
+ endpoint,
4973
+ method,
4974
+ requestId: resolveRequestId3(response.headers),
4975
+ body: parsed
4976
+ });
4977
+ }
4978
+ return parsed;
4979
+ }
4980
+ function createRealtimeConnection(config, options) {
4981
+ if (!config.wsUrl) {
4982
+ throw new Error(
4983
+ "Athena chat WebSocket URL is not configured. Pass createClient({ url }) for unified routing or set chat.wsUrl / chatWsUrl explicitly."
4984
+ );
4985
+ }
4986
+ const wsFactory = config.webSocketFactory ?? globalThis.WebSocket;
4987
+ if (!wsFactory) {
4988
+ throw new Error(
4989
+ "No WebSocket implementation is available. Provide chat.webSocketFactory in createClient(...) or run in a runtime with global WebSocket support."
4990
+ );
4991
+ }
4992
+ const socket = createSocket(wsFactory, config.wsUrl, options?.protocols);
4993
+ const send = (command) => {
4994
+ socket.send(JSON.stringify(command));
4995
+ };
4996
+ if (options?.onMessage) {
4997
+ const listener = (event) => {
4998
+ const messageEvent = event;
4999
+ const raw = messageEvent?.data;
5000
+ if (typeof raw !== "string") {
5001
+ return;
5002
+ }
5003
+ try {
5004
+ options.onMessage?.(JSON.parse(raw));
5005
+ } catch {
5006
+ options.onMessage?.({ type: "error", error: "Invalid JSON message from Athena chat realtime gateway." });
5007
+ }
5008
+ };
5009
+ if (typeof socket.addEventListener === "function") {
5010
+ socket.addEventListener("message", listener);
5011
+ } else {
5012
+ socket.onmessage = listener;
5013
+ }
5014
+ }
5015
+ const hello = (command) => {
5016
+ send({
5017
+ type: "auth.hello",
5018
+ token: command?.token,
5019
+ room_subscriptions: command?.room_subscriptions
5020
+ });
5021
+ };
5022
+ if (options?.hello) {
5023
+ const onOpen = () => hello({
5024
+ token: options.hello?.token ?? void 0,
5025
+ room_subscriptions: options.hello?.room_subscriptions ?? void 0
5026
+ });
5027
+ if (typeof socket.addEventListener === "function") {
5028
+ socket.addEventListener("open", onOpen);
5029
+ } else {
5030
+ socket.onopen = onOpen;
5031
+ }
5032
+ }
5033
+ return {
5034
+ socket,
5035
+ send,
5036
+ hello,
5037
+ subscribe(roomId, fromSeq) {
5038
+ send({
5039
+ type: "chat.subscribe",
5040
+ room_id: roomId,
5041
+ from_seq: fromSeq ?? void 0
5042
+ });
5043
+ },
5044
+ unsubscribe(roomId) {
5045
+ send({
5046
+ type: "chat.unsubscribe",
5047
+ room_id: roomId
5048
+ });
5049
+ },
5050
+ resume(rooms) {
5051
+ send({
5052
+ type: "chat.resume",
5053
+ rooms
5054
+ });
5055
+ },
5056
+ typingStart(roomId) {
5057
+ send({
5058
+ type: "chat.typing.start",
5059
+ room_id: roomId
5060
+ });
5061
+ },
5062
+ typingStop(roomId) {
5063
+ send({
5064
+ type: "chat.typing.stop",
5065
+ room_id: roomId
5066
+ });
5067
+ },
5068
+ presenceHeartbeat(activeRoomId) {
5069
+ send({
5070
+ type: "chat.presence.heartbeat",
5071
+ active_room_id: activeRoomId ?? void 0
5072
+ });
5073
+ },
5074
+ readUpTo(roomId, input) {
5075
+ send({
5076
+ type: "chat.read.up_to",
5077
+ room_id: roomId,
5078
+ message_id: input?.message_id ?? void 0,
5079
+ seq: input?.seq ?? void 0
5080
+ });
5081
+ },
5082
+ ping(at = (/* @__PURE__ */ new Date()).toISOString()) {
5083
+ send({
5084
+ type: "ping",
5085
+ at
5086
+ });
5087
+ },
5088
+ close(code, reason) {
5089
+ socket.close(code, reason);
5090
+ }
5091
+ };
5092
+ }
5093
+ function createChatModule(config) {
5094
+ const realtime = {
5095
+ info(options) {
5096
+ const realtimeInfoUrl = config.realtimeInfoUrl ?? deriveRealtimeInfoUrl(config.wsUrl);
5097
+ if (!realtimeInfoUrl) {
5098
+ throw new Error(
5099
+ "Athena chat realtime info URL is not configured. Pass createClient({ url }) for unified routing or set chat.wsUrl / chatWsUrl explicitly."
5100
+ );
5101
+ }
5102
+ return request(
5103
+ {
5104
+ ...config,
5105
+ baseUrl: realtimeInfoUrl
5106
+ },
5107
+ "GET",
5108
+ "",
5109
+ options
5110
+ );
5111
+ },
5112
+ connect(options) {
5113
+ return createRealtimeConnection(config, options);
5114
+ }
5115
+ };
5116
+ return {
5117
+ room: {
5118
+ list(query, options) {
5119
+ return request(
5120
+ config,
5121
+ "GET",
5122
+ `/rooms${encodeQuery(query)}`,
5123
+ options
5124
+ );
5125
+ },
5126
+ create(input, options) {
5127
+ return request(config, "POST", "/rooms", options, input);
5128
+ },
5129
+ get(roomId, options) {
5130
+ return request(
5131
+ config,
5132
+ "GET",
5133
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}`,
5134
+ options
5135
+ );
5136
+ },
5137
+ update(roomId, input, options) {
5138
+ return request(
5139
+ config,
5140
+ "PATCH",
5141
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}`,
5142
+ options,
5143
+ input
5144
+ );
5145
+ },
5146
+ archive(roomId, options) {
5147
+ return request(
5148
+ config,
5149
+ "POST",
5150
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/archive`,
5151
+ options
5152
+ );
5153
+ },
5154
+ readCursor: {
5155
+ upTo(roomId, input, options) {
5156
+ return request(
5157
+ config,
5158
+ "POST",
5159
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/read-cursor`,
5160
+ options,
5161
+ input ?? {}
5162
+ );
5163
+ }
5164
+ },
5165
+ member: {
5166
+ list(roomId, options) {
5167
+ return request(
5168
+ config,
5169
+ "GET",
5170
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/members`,
5171
+ options
5172
+ );
5173
+ },
5174
+ add(roomId, input, options) {
5175
+ return request(
5176
+ config,
5177
+ "POST",
5178
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/members`,
5179
+ options,
5180
+ input
5181
+ );
5182
+ },
5183
+ remove(roomId, userId, options) {
5184
+ return request(
5185
+ config,
5186
+ "DELETE",
5187
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/members/${encodePathSegment(userId, "chat user ID")}`,
5188
+ options
5189
+ );
5190
+ }
5191
+ },
5192
+ message: {
5193
+ list(roomId, query, options) {
5194
+ return request(
5195
+ config,
5196
+ "GET",
5197
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages${encodeQuery(query)}`,
5198
+ options
5199
+ );
5200
+ },
5201
+ send(roomId, input, options) {
5202
+ return request(
5203
+ config,
5204
+ "POST",
5205
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages`,
5206
+ options,
5207
+ input
5208
+ );
5209
+ },
5210
+ update(roomId, messageId, input, options) {
5211
+ return request(
5212
+ config,
5213
+ "PATCH",
5214
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages/${encodePathSegment(messageId, "chat message ID")}`,
5215
+ options,
5216
+ input
5217
+ );
5218
+ },
5219
+ delete(roomId, messageId, options) {
5220
+ return request(
5221
+ config,
5222
+ "DELETE",
5223
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages/${encodePathSegment(messageId, "chat message ID")}`,
5224
+ options
5225
+ );
5226
+ }
5227
+ }
5228
+ },
5229
+ message: {
5230
+ reaction: {
5231
+ add(messageId, input, options) {
5232
+ return request(
5233
+ config,
5234
+ "POST",
5235
+ `/messages/${encodePathSegment(messageId, "chat message ID")}/reactions`,
5236
+ options,
5237
+ input
5238
+ );
5239
+ },
5240
+ remove(messageId, emoji, options) {
5241
+ return request(
5242
+ config,
5243
+ "DELETE",
5244
+ `/messages/${encodePathSegment(messageId, "chat message ID")}/reactions/${encodePathSegment(emoji, "reaction emoji")}`,
5245
+ options
5246
+ );
5247
+ }
5248
+ },
5249
+ search(input, options) {
5250
+ return request(
5251
+ config,
5252
+ "POST",
5253
+ "/messages/search",
5254
+ options,
5255
+ input
5256
+ );
5257
+ }
5258
+ },
5259
+ realtime
5260
+ };
5261
+ }
5262
+
4687
5263
  // src/client-builder.ts
4688
5264
  var DEFAULT_BACKEND = { type: "athena" };
4689
5265
  function toBackendConfig(value) {
@@ -4896,7 +5472,7 @@ var BOOLEAN_SAFE_OPERATORS = /* @__PURE__ */ new Set([
4896
5472
  "ilike",
4897
5473
  "is"
4898
5474
  ]);
4899
- function isRecord7(value) {
5475
+ function isRecord8(value) {
4900
5476
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
4901
5477
  }
4902
5478
  function isUuidString(value) {
@@ -4909,7 +5485,7 @@ function shouldUseUuidTextComparison(column, value) {
4909
5485
  return typeof value === "string" && isUuidString(value) && isUuidIdentifierColumn(column);
4910
5486
  }
4911
5487
  function isRelationSelectNode(value) {
4912
- return isRecord7(value) && isRecord7(value.select);
5488
+ return isRecord8(value) && isRecord8(value.select);
4913
5489
  }
4914
5490
  function normalizeIdentifier(value, label) {
4915
5491
  const normalized = value.trim();
@@ -4965,7 +5541,7 @@ function compileRelationToken(key, node) {
4965
5541
  return `${prefix}${relationToken}(${nested})`;
4966
5542
  }
4967
5543
  function compileSelectShape(select) {
4968
- if (!isRecord7(select)) {
5544
+ if (!isRecord8(select)) {
4969
5545
  throw new Error("findMany select must be an object");
4970
5546
  }
4971
5547
  const tokens = [];
@@ -4989,7 +5565,7 @@ function compileSelectShape(select) {
4989
5565
  return tokens.join(",");
4990
5566
  }
4991
5567
  function selectShapeUsesRelationSchema(select) {
4992
- if (!isRecord7(select)) {
5568
+ if (!isRecord8(select)) {
4993
5569
  return false;
4994
5570
  }
4995
5571
  for (const rawValue of Object.values(select)) {
@@ -5007,7 +5583,7 @@ function selectShapeUsesRelationSchema(select) {
5007
5583
  }
5008
5584
  function compileColumnWhere(column, input) {
5009
5585
  const normalizedColumn = normalizeIdentifier(column, "where column");
5010
- if (!isRecord7(input)) {
5586
+ if (!isRecord8(input)) {
5011
5587
  return [buildGatewayCondition("eq", normalizedColumn, input)];
5012
5588
  }
5013
5589
  const conditions = [];
@@ -5035,7 +5611,7 @@ function compileColumnWhere(column, input) {
5035
5611
  return conditions;
5036
5612
  }
5037
5613
  function compileBooleanExpressionTerms(clause, label) {
5038
- if (!isRecord7(clause)) {
5614
+ if (!isRecord8(clause)) {
5039
5615
  throw new Error(`findMany where.${label} clauses must be objects`);
5040
5616
  }
5041
5617
  const entries = Object.entries(clause).filter(([, value]) => value !== void 0);
@@ -5044,7 +5620,7 @@ function compileBooleanExpressionTerms(clause, label) {
5044
5620
  }
5045
5621
  const [rawColumn, rawValue] = entries[0];
5046
5622
  const column = normalizeIdentifier(rawColumn, `where.${label} column`);
5047
- if (!isRecord7(rawValue)) {
5623
+ if (!isRecord8(rawValue)) {
5048
5624
  return [`${column}.eq.${stringifyFilterValue(rawValue)}`];
5049
5625
  }
5050
5626
  const operatorEntries = Object.entries(rawValue).filter(([, value]) => value !== void 0);
@@ -5068,7 +5644,7 @@ function compileWhere(where) {
5068
5644
  if (where === void 0) {
5069
5645
  return void 0;
5070
5646
  }
5071
- if (!isRecord7(where)) {
5647
+ if (!isRecord8(where)) {
5072
5648
  throw new Error("findMany where must be an object");
5073
5649
  }
5074
5650
  const conditions = [];
@@ -5118,7 +5694,7 @@ function compileOrderBy(orderBy) {
5118
5694
  if (orderBy === void 0) {
5119
5695
  return void 0;
5120
5696
  }
5121
- if (!isRecord7(orderBy)) {
5697
+ if (!isRecord8(orderBy)) {
5122
5698
  throw new Error("findMany orderBy must be an object");
5123
5699
  }
5124
5700
  if ("column" in orderBy) {
@@ -5293,11 +5869,11 @@ function toFindManyAstOrder(order) {
5293
5869
  ascending: order.direction !== "descending"
5294
5870
  };
5295
5871
  }
5296
- function isRecord8(value) {
5872
+ function isRecord9(value) {
5297
5873
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
5298
5874
  }
5299
5875
  function normalizeFindManyAstColumnPredicate(value) {
5300
- if (!isRecord8(value)) {
5876
+ if (!isRecord9(value)) {
5301
5877
  return {
5302
5878
  eq: value
5303
5879
  };
@@ -5321,7 +5897,7 @@ function normalizeFindManyAstBooleanOperand(clause) {
5321
5897
  return normalized;
5322
5898
  }
5323
5899
  function normalizeFindManyAstWhere(where) {
5324
- if (!where || !isRecord8(where)) {
5900
+ if (!where || !isRecord9(where)) {
5325
5901
  return where;
5326
5902
  }
5327
5903
  const normalized = {};
@@ -5335,7 +5911,7 @@ function normalizeFindManyAstWhere(where) {
5335
5911
  );
5336
5912
  continue;
5337
5913
  }
5338
- if (key === "not" && isRecord8(value)) {
5914
+ if (key === "not" && isRecord9(value)) {
5339
5915
  normalized.not = normalizeFindManyAstBooleanOperand(
5340
5916
  value
5341
5917
  );
@@ -5346,7 +5922,7 @@ function normalizeFindManyAstWhere(where) {
5346
5922
  return normalized;
5347
5923
  }
5348
5924
  function predicateRequiresUuidQueryFallback(column, value) {
5349
- if (!isRecord8(value)) {
5925
+ if (!isRecord9(value)) {
5350
5926
  return shouldUseUuidTextComparison(column, value);
5351
5927
  }
5352
5928
  const eqValue = value.eq;
@@ -5364,7 +5940,7 @@ function booleanOperandRequiresUuidQueryFallback(clause) {
5364
5940
  return false;
5365
5941
  }
5366
5942
  function findManyAstWhereRequiresLegacyTransport(where) {
5367
- if (!where || !isRecord8(where)) {
5943
+ if (!where || !isRecord9(where)) {
5368
5944
  return false;
5369
5945
  }
5370
5946
  for (const [key, value] of Object.entries(where)) {
@@ -5379,7 +5955,7 @@ function findManyAstWhereRequiresLegacyTransport(where) {
5379
5955
  }
5380
5956
  continue;
5381
5957
  }
5382
- if (key === "not" && isRecord8(value)) {
5958
+ if (key === "not" && isRecord9(value)) {
5383
5959
  if (booleanOperandRequiresUuidQueryFallback(value)) {
5384
5960
  return true;
5385
5961
  }
@@ -5922,6 +6498,7 @@ function resolveAthenaModelTargetTableName(target, options = {}) {
5922
6498
  var DEFAULT_COLUMNS = "*";
5923
6499
  var SAFE_CAST_PATTERN = /^[a-z_][a-z0-9_]*(?:\[\])?$/i;
5924
6500
  var ATHENA_NORMALIZED_ERROR_KEY = "__athenaNormalizedError";
6501
+ var SDK_NAME4 = "xylex-group/athena";
5925
6502
  function formatResult(response) {
5926
6503
  const result = {
5927
6504
  data: response.data ?? null,
@@ -5998,7 +6575,7 @@ async function executeExperimentalRead(experimental, runner) {
5998
6575
  throw error;
5999
6576
  }
6000
6577
  }
6001
- function isRecord9(value) {
6578
+ function isRecord10(value) {
6002
6579
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6003
6580
  }
6004
6581
  function firstNonEmptyString2(...values) {
@@ -6010,8 +6587,8 @@ function firstNonEmptyString2(...values) {
6010
6587
  return void 0;
6011
6588
  }
6012
6589
  function resolveStructuredErrorPayload2(raw) {
6013
- if (!isRecord9(raw)) return null;
6014
- return isRecord9(raw.error) ? raw.error : raw;
6590
+ if (!isRecord10(raw)) return null;
6591
+ return isRecord10(raw.error) ? raw.error : raw;
6015
6592
  }
6016
6593
  function resolveStructuredErrorDetails(payload, message) {
6017
6594
  if (!payload || !("details" in payload)) {
@@ -6027,7 +6604,7 @@ function resolveStructuredErrorDetails(payload, message) {
6027
6604
  return details;
6028
6605
  }
6029
6606
  function createResultError(response, result, normalized) {
6030
- const rawRecord = isRecord9(response.raw) ? response.raw : null;
6607
+ const rawRecord = isRecord10(response.raw) ? response.raw : null;
6031
6608
  const payload = resolveStructuredErrorPayload2(response.raw);
6032
6609
  const message = firstNonEmptyString2(
6033
6610
  response.error,
@@ -6090,6 +6667,43 @@ function asAthenaJsonObject(value) {
6090
6667
  function asAthenaJsonObjectArray(values) {
6091
6668
  return values;
6092
6669
  }
6670
+ function parseArbitraryResponseBody(rawText, contentType) {
6671
+ if (!rawText) {
6672
+ return null;
6673
+ }
6674
+ const contentTypeSuggestsJson = contentType?.toLowerCase().includes("application/json") ?? false;
6675
+ const looksJson = contentTypeSuggestsJson || rawText.startsWith("{") || rawText.startsWith("[");
6676
+ if (!looksJson) {
6677
+ return rawText;
6678
+ }
6679
+ try {
6680
+ return JSON.parse(rawText);
6681
+ } catch {
6682
+ return rawText;
6683
+ }
6684
+ }
6685
+ function toRequestQueryString(query) {
6686
+ if (!query) {
6687
+ return "";
6688
+ }
6689
+ const params = new URLSearchParams();
6690
+ for (const [key, value] of Object.entries(query)) {
6691
+ if (value === void 0 || value === null) {
6692
+ continue;
6693
+ }
6694
+ if (Array.isArray(value)) {
6695
+ for (const item of value) {
6696
+ if (item !== void 0 && item !== null) {
6697
+ params.append(key, String(item));
6698
+ }
6699
+ }
6700
+ continue;
6701
+ }
6702
+ params.set(key, String(value));
6703
+ }
6704
+ const encoded = params.toString();
6705
+ return encoded ? `?${encoded}` : "";
6706
+ }
6093
6707
  function normalizeSelectColumnsInput(columns) {
6094
6708
  if (columns === void 0) {
6095
6709
  return void 0;
@@ -7396,6 +8010,8 @@ var ATHENA_ENV_GATEWAY_URL_KEYS = [
7396
8010
  "NEXT_PUBLIC_ATHENA_DB_API_URL"
7397
8011
  ];
7398
8012
  var ATHENA_ENV_AUTH_URL_KEYS = ["ATHENA_AUTH_URL", "NEXT_PUBLIC_ATHENA_AUTH_URL"];
8013
+ var ATHENA_ENV_CHAT_URL_KEYS = ["ATHENA_CHAT_URL", "NEXT_PUBLIC_ATHENA_CHAT_URL"];
8014
+ var ATHENA_ENV_CHAT_WS_URL_KEYS = ["ATHENA_CHAT_WS_URL", "NEXT_PUBLIC_ATHENA_CHAT_WS_URL"];
7399
8015
  var ATHENA_ENV_STORAGE_URL_KEYS = ["ATHENA_STORAGE_URL", "NEXT_PUBLIC_ATHENA_STORAGE_URL"];
7400
8016
  var ATHENA_ENV_KEY_KEYS = [
7401
8017
  "ATHENA_API_KEY",
@@ -7476,6 +8092,15 @@ function appendServicePath(baseUrl, segment) {
7476
8092
  const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(baseUrl, { label: "Athena public base URL" });
7477
8093
  return `${normalizedBaseUrl}/${segment.replace(/^\/+/, "")}`;
7478
8094
  }
8095
+ function appendRealtimeGatewayPath(baseUrl) {
8096
+ const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(baseUrl, { label: "Athena public base URL" });
8097
+ const wsUrl = new URL(normalizedBaseUrl);
8098
+ wsUrl.protocol = wsUrl.protocol === "https:" ? "wss:" : "ws:";
8099
+ wsUrl.pathname = `${wsUrl.pathname.replace(/\/+$/, "")}/wss/gateway`;
8100
+ wsUrl.search = "";
8101
+ wsUrl.hash = "";
8102
+ return wsUrl.toString();
8103
+ }
7479
8104
  function resolveServiceUrlOverride(value, label) {
7480
8105
  return resolveClientServiceBaseUrl(value, label);
7481
8106
  }
@@ -7484,6 +8109,8 @@ function resolveServiceUrls(config) {
7484
8109
  return {
7485
8110
  dbUrl: resolveServiceUrlOverride(config.db?.url, "Athena DB base URL") ?? resolveServiceUrlOverride(config.gateway?.url, "Athena gateway base URL") ?? resolveServiceUrlOverride(config.dbUrl, "Athena DB base URL") ?? resolveServiceUrlOverride(config.gatewayUrl, "Athena gateway base URL") ?? (baseUrl ? appendServicePath(baseUrl, "db") : void 0),
7486
8111
  authUrl: resolveServiceUrlOverride(config.auth?.url, "Athena auth base URL") ?? resolveServiceUrlOverride(config.auth?.baseUrl, "Athena auth base URL") ?? resolveServiceUrlOverride(config.authUrl, "Athena auth base URL") ?? (baseUrl ? appendServicePath(baseUrl, "auth") : void 0),
8112
+ chatUrl: resolveServiceUrlOverride(config.chat?.url, "Athena chat base URL") ?? resolveServiceUrlOverride(config.chatUrl, "Athena chat base URL") ?? (baseUrl ? appendServicePath(baseUrl, "chat") : void 0),
8113
+ chatWsUrl: normalizeOptionalString(config.chat?.wsUrl) ?? normalizeOptionalString(config.chatWsUrl) ?? (baseUrl ? appendRealtimeGatewayPath(baseUrl) : void 0),
7487
8114
  storageUrl: resolveServiceUrlOverride(config.storage?.url, "Athena storage base URL") ?? resolveServiceUrlOverride(config.storageUrl, "Athena storage base URL") ?? (baseUrl ? appendServicePath(baseUrl, "storage") : void 0)
7488
8115
  };
7489
8116
  }
@@ -7576,6 +8203,7 @@ function mergeClientOverrideOptions(base, overrides) {
7576
8203
  } : void 0,
7577
8204
  db: base.db ? { ...base.db } : void 0,
7578
8205
  gateway: base.gateway ? { ...base.gateway } : void 0,
8206
+ chat: base.chat ? { ...base.chat } : void 0,
7579
8207
  storage: base.storage ? { ...base.storage } : void 0
7580
8208
  };
7581
8209
  }
@@ -7586,6 +8214,7 @@ function mergeClientOverrideOptions(base, overrides) {
7586
8214
  auth: mergeAuthClientOptions(base.auth, overrides.auth),
7587
8215
  db: mergeServiceUrlOverrides(base.db, overrides.db),
7588
8216
  gateway: mergeServiceUrlOverrides(base.gateway, overrides.gateway),
8217
+ chat: mergeServiceUrlOverrides(base.chat, overrides.chat),
7589
8218
  storage: mergeServiceUrlOverrides(base.storage, overrides.storage)
7590
8219
  };
7591
8220
  }
@@ -7644,6 +8273,9 @@ function resolveCreateClientConfig(config) {
7644
8273
  headers: config.headers,
7645
8274
  auth: config.auth,
7646
8275
  authUrl: resolvedUrls.authUrl,
8276
+ chat: config.chat,
8277
+ chatUrl: resolvedUrls.chatUrl,
8278
+ chatWsUrl: resolvedUrls.chatWsUrl,
7647
8279
  storageUrl: resolvedUrls.storageUrl,
7648
8280
  experimental: config.experimental
7649
8281
  };
@@ -7728,6 +8360,119 @@ function createClientFromConfig(config, sourceConfig) {
7728
8360
  queryTracer
7729
8361
  );
7730
8362
  const db = createDbModule({ from, rpc, query });
8363
+ const chat = createChatModule({
8364
+ baseUrl: config.chatUrl,
8365
+ apiKey: config.apiKey,
8366
+ client: config.client,
8367
+ headers: config.headers,
8368
+ bearerToken: normalizedAuthConfig?.bearerToken,
8369
+ cookie: normalizedAuthConfig?.cookie,
8370
+ sessionToken: normalizedAuthConfig?.sessionToken,
8371
+ forceNoCache: config.forceNoCache,
8372
+ wsUrl: config.chatWsUrl,
8373
+ webSocketFactory: config.chat?.webSocketFactory ?? void 0
8374
+ });
8375
+ const request2 = async (options) => {
8376
+ const method = options.method ?? "GET";
8377
+ const responseType = options.responseType ?? "json";
8378
+ const service = options.service ?? "db";
8379
+ const baseUrlByService = {
8380
+ db: config.baseUrl,
8381
+ auth: config.authUrl,
8382
+ chat: config.chatUrl,
8383
+ storage: config.storageUrl
8384
+ };
8385
+ const resolvedBaseUrl = options.url ?? baseUrlByService[service];
8386
+ if (!resolvedBaseUrl) {
8387
+ throw new Error(
8388
+ `Athena ${service} base URL is not configured. Pass createClient({ url }) for unified routing or set the service-specific URL first.`
8389
+ );
8390
+ }
8391
+ const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(resolvedBaseUrl, {
8392
+ label: `Athena ${service} base URL`
8393
+ });
8394
+ const normalizedPath = options.url ? "" : (() => {
8395
+ const path = options.path?.trim();
8396
+ if (!path) {
8397
+ throw new Error("client.request(...) requires either an absolute url or a non-empty path.");
8398
+ }
8399
+ return path.startsWith("/") ? path : `/${path}`;
8400
+ })();
8401
+ const targetUrl = options.url ? `${normalizedBaseUrl}${toRequestQueryString(options.query)}` : `${normalizedBaseUrl}${normalizedPath}${toRequestQueryString(options.query)}`;
8402
+ const headers = {
8403
+ "X-Athena-Sdk": buildSdkHeaderValue(SDK_NAME4),
8404
+ ...config.headers ?? {},
8405
+ ...options.headers ?? {}
8406
+ };
8407
+ if (service !== "auth") {
8408
+ headers.apikey = headers.apikey ?? config.apiKey;
8409
+ headers["x-api-key"] = headers["x-api-key"] ?? config.apiKey;
8410
+ if (config.client && !hasHeaderIgnoreCase(headers, "X-Athena-Client")) {
8411
+ headers["X-Athena-Client"] = config.client;
8412
+ }
8413
+ if (config.userId && !hasHeaderIgnoreCase(headers, "X-User-Id")) {
8414
+ headers["X-User-Id"] = config.userId;
8415
+ }
8416
+ if (config.organizationId && !hasHeaderIgnoreCase(headers, "X-Organization-Id")) {
8417
+ headers["X-Organization-Id"] = config.organizationId;
8418
+ }
8419
+ if (normalizedAuthConfig?.sessionToken && !hasHeaderIgnoreCase(headers, "X-Athena-Auth-Session-Token")) {
8420
+ headers["X-Athena-Auth-Session-Token"] = normalizedAuthConfig.sessionToken;
8421
+ }
8422
+ if (normalizedAuthConfig?.bearerToken && !hasHeaderIgnoreCase(headers, "X-Athena-Auth-Bearer-Token")) {
8423
+ headers["X-Athena-Auth-Bearer-Token"] = normalizedAuthConfig.bearerToken;
8424
+ }
8425
+ if (normalizedAuthConfig?.cookie && !hasHeaderIgnoreCase(headers, "Cookie")) {
8426
+ headers.Cookie = normalizedAuthConfig.cookie;
8427
+ }
8428
+ } else {
8429
+ const authApiKey = normalizedAuthConfig?.apiKey ?? config.apiKey;
8430
+ if (authApiKey && !hasHeaderIgnoreCase(headers, "x-api-key")) {
8431
+ headers.apikey = headers.apikey ?? authApiKey;
8432
+ headers["x-api-key"] = headers["x-api-key"] ?? authApiKey;
8433
+ }
8434
+ if (normalizedAuthConfig?.bearerToken && !hasHeaderIgnoreCase(headers, "Authorization")) {
8435
+ headers.Authorization = `Bearer ${normalizedAuthConfig.bearerToken}`;
8436
+ }
8437
+ if (normalizedAuthConfig?.cookie && !hasHeaderIgnoreCase(headers, "Cookie")) {
8438
+ headers.Cookie = normalizedAuthConfig.cookie;
8439
+ }
8440
+ if (normalizedAuthConfig?.sessionToken && !hasHeaderIgnoreCase(headers, "X-Athena-Auth-Session-Token")) {
8441
+ headers["X-Athena-Auth-Session-Token"] = normalizedAuthConfig.sessionToken;
8442
+ }
8443
+ }
8444
+ const shouldSendJsonBody = options.body !== void 0 && options.body !== null && !(options.body instanceof FormData) && !(options.body instanceof Blob) && !(options.body instanceof URLSearchParams) && !(options.body instanceof ArrayBuffer) && !ArrayBuffer.isView(options.body) && typeof options.body !== "string";
8445
+ if (shouldSendJsonBody && !hasHeaderIgnoreCase(headers, "Content-Type")) {
8446
+ headers["Content-Type"] = "application/json";
8447
+ }
8448
+ const response = await fetch(targetUrl, {
8449
+ method,
8450
+ headers,
8451
+ body: options.body === void 0 || options.body === null ? void 0 : shouldSendJsonBody ? JSON.stringify(options.body) : options.body,
8452
+ signal: options.signal,
8453
+ credentials: options.credentials
8454
+ });
8455
+ if (responseType === "response") {
8456
+ return {
8457
+ ok: response.ok,
8458
+ status: response.status,
8459
+ statusText: response.statusText,
8460
+ headers: response.headers,
8461
+ data: null,
8462
+ raw: response
8463
+ };
8464
+ }
8465
+ const rawText = await response.text();
8466
+ const parsed = responseType === "text" ? rawText : parseArbitraryResponseBody(rawText, response.headers.get("content-type"));
8467
+ return {
8468
+ ok: response.ok,
8469
+ status: response.status,
8470
+ statusText: response.statusText,
8471
+ headers: response.headers,
8472
+ data: parsed,
8473
+ raw: response
8474
+ };
8475
+ };
7731
8476
  const withContext = (context) => createClientFromInput(
7732
8477
  mergeClientOverrideOptions(sourceConfig, toClientContextOverrides(context))
7733
8478
  );
@@ -7743,8 +8488,10 @@ function createClientFromConfig(config, sourceConfig) {
7743
8488
  db,
7744
8489
  rpc,
7745
8490
  query,
8491
+ request: request2,
7746
8492
  verifyConnection: gateway.verifyConnection,
7747
8493
  auth: auth.auth,
8494
+ chat,
7748
8495
  withContext,
7749
8496
  withSession,
7750
8497
  withOptions: authWithOptions
@@ -7789,6 +8536,8 @@ var AthenaClient = class {
7789
8536
  const url = options.url ?? readFirstEnvValue(env, ATHENA_ENV_URL_KEYS);
7790
8537
  const gatewayUrl = options.gatewayUrl ?? readFirstEnvValue(env, ATHENA_ENV_GATEWAY_URL_KEYS);
7791
8538
  const authUrl = options.authUrl ?? readFirstEnvValue(env, ATHENA_ENV_AUTH_URL_KEYS);
8539
+ const chatUrl = options.chatUrl ?? readFirstEnvValue(env, ATHENA_ENV_CHAT_URL_KEYS);
8540
+ const chatWsUrl = options.chatWsUrl ?? readFirstEnvValue(env, ATHENA_ENV_CHAT_WS_URL_KEYS);
7792
8541
  const storageUrl = options.storageUrl ?? readFirstEnvValue(env, ATHENA_ENV_STORAGE_URL_KEYS);
7793
8542
  const key = options.key ?? readFirstEnvValue(env, ATHENA_ENV_KEY_KEYS);
7794
8543
  const client = options.client ?? readFirstEnvValue(env, ATHENA_ENV_CLIENT_KEYS);
@@ -7803,6 +8552,8 @@ var AthenaClient = class {
7803
8552
  url,
7804
8553
  gatewayUrl,
7805
8554
  authUrl,
8555
+ chatUrl,
8556
+ chatWsUrl,
7806
8557
  storageUrl,
7807
8558
  key,
7808
8559
  client
@@ -7843,6 +8594,8 @@ function createAdapterClient(options, context) {
7843
8594
  url: options?.url,
7844
8595
  gatewayUrl: options?.gatewayUrl,
7845
8596
  authUrl: options?.authUrl,
8597
+ chatUrl: options?.chatUrl,
8598
+ chatWsUrl: options?.chatWsUrl,
7846
8599
  storageUrl: options?.storageUrl,
7847
8600
  key: options?.key,
7848
8601
  client: options?.client,