@xylex-group/athena 2.9.0 → 2.10.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 +1 -1
  2. package/dist/browser.cjs +828 -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 +825 -75
  7. package/dist/browser.js.map +1 -1
  8. package/dist/cli/index.cjs +748 -40
  9. package/dist/cli/index.cjs.map +1 -1
  10. package/dist/cli/index.js +748 -40
  11. package/dist/cli/index.js.map +1 -1
  12. package/dist/{client-CfAE_QOj.d.cts → client-B7EQ_hPV.d.cts} +506 -22
  13. package/dist/{client-D6EIJdQS.d.ts → client-BYii6dU9.d.ts} +506 -22
  14. package/dist/index.cjs +828 -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 +825 -75
  19. package/dist/index.js.map +1 -1
  20. package/dist/{react-email-BvJ3fj_F.d.cts → module-DC96HJa3.d.cts} +97 -2
  21. package/dist/{react-email-PLAJuZuO.d.ts → module-DbHlxpeR.d.ts} +97 -2
  22. package/dist/next/client.cjs +756 -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 +756 -40
  27. package/dist/next/client.js.map +1 -1
  28. package/dist/next/server.cjs +756 -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 +756 -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-BMVGMnti.d.cts} +3 -1
  41. package/dist/{shared-BiJvoURI.d.ts → shared-DRptGBWP.d.ts} +3 -1
  42. package/package.json +1 -1
@@ -1980,8 +1980,8 @@ function parseCookies(cookieHeader) {
1980
1980
  });
1981
1981
  return cookieMap;
1982
1982
  }
1983
- var getSessionCookie = (request, config) => {
1984
- const cookies = (request instanceof Headers || !("headers" in request) ? request : request.headers).get("cookie");
1983
+ var getSessionCookie = (request2, config) => {
1984
+ const cookies = (request2 instanceof Headers || !("headers" in request2) ? request2 : request2.headers).get("cookie");
1985
1985
  if (!cookies) {
1986
1986
  return null;
1987
1987
  }
@@ -2004,7 +2004,7 @@ var getSessionCookie = (request, config) => {
2004
2004
 
2005
2005
  // package.json
2006
2006
  var package_default = {
2007
- version: "2.9.0"
2007
+ version: "2.10.0"
2008
2008
  };
2009
2009
 
2010
2010
  // src/sdk-version.ts
@@ -2985,6 +2985,50 @@ function mergeCallOptions(base, override) {
2985
2985
  }
2986
2986
  };
2987
2987
  }
2988
+ function copyDefinedField(target, source, targetKey, sourceKey) {
2989
+ if (!(sourceKey in source)) {
2990
+ return;
2991
+ }
2992
+ const value = source[sourceKey];
2993
+ if (value !== void 0) {
2994
+ target[targetKey] = value;
2995
+ }
2996
+ }
2997
+ function normalizeAdminEmailTemplatePayload(payload) {
2998
+ const normalized = { ...payload };
2999
+ copyDefinedField(normalized, payload, "template_key", "templateKey");
3000
+ copyDefinedField(normalized, payload, "event_type", "eventType");
3001
+ copyDefinedField(normalized, payload, "subject_template", "subjectTemplate");
3002
+ copyDefinedField(normalized, payload, "text_template", "textTemplate");
3003
+ copyDefinedField(normalized, payload, "html_template", "htmlTemplate");
3004
+ copyDefinedField(normalized, payload, "variable_bindings", "variableBindings");
3005
+ copyDefinedField(normalized, payload, "attachment_failure_mode", "attachmentFailureMode");
3006
+ copyDefinedField(normalized, payload, "is_active", "isActive");
3007
+ return normalized;
3008
+ }
3009
+ function toReactEmailTemplateCompatibilityInput(input) {
3010
+ const payload = input;
3011
+ const compatibility = { ...payload };
3012
+ copyDefinedField(compatibility, payload, "templateKey", "template_key");
3013
+ copyDefinedField(compatibility, payload, "eventType", "event_type");
3014
+ copyDefinedField(compatibility, payload, "subjectTemplate", "subject_template");
3015
+ copyDefinedField(compatibility, payload, "textTemplate", "text_template");
3016
+ copyDefinedField(compatibility, payload, "htmlTemplate", "html_template");
3017
+ copyDefinedField(compatibility, payload, "variableBindings", "variable_bindings");
3018
+ copyDefinedField(compatibility, payload, "attachmentFailureMode", "attachment_failure_mode");
3019
+ copyDefinedField(compatibility, payload, "isActive", "is_active");
3020
+ return compatibility;
3021
+ }
3022
+ function normalizeAdminEmailTemplateSendPayload(payload) {
3023
+ const normalized = { ...payload };
3024
+ copyDefinedField(normalized, payload, "template_id", "templateId");
3025
+ copyDefinedField(normalized, payload, "recipient_email", "recipientEmail");
3026
+ copyDefinedField(normalized, payload, "render_variables", "renderVariables");
3027
+ copyDefinedField(normalized, payload, "user_id", "userId");
3028
+ copyDefinedField(normalized, payload, "organization_id", "organizationId");
3029
+ copyDefinedField(normalized, payload, "session_token", "sessionToken");
3030
+ return normalized;
3031
+ }
2988
3032
  function toSessionGuardFailure(sessionResult) {
2989
3033
  if (sessionResult.status === 401 || sessionResult.data == null) {
2990
3034
  return {
@@ -3291,7 +3335,7 @@ function createAuthClient(config = {}) {
3291
3335
  ...config,
3292
3336
  baseUrl: normalizedBaseUrl
3293
3337
  };
3294
- const request = (input, options) => {
3338
+ const request2 = (input, options) => {
3295
3339
  const method = input.method ?? (input.body !== void 0 ? "POST" : inferDefaultMethod(input.endpoint));
3296
3340
  const mergedOptions = mergeCallOptions(input.fetchOptions, options);
3297
3341
  return callAuthEndpoint(
@@ -3304,7 +3348,7 @@ function createAuthClient(config = {}) {
3304
3348
  };
3305
3349
  const postGeneric = (endpoint, input, options) => {
3306
3350
  const { payload, fetchOptions } = extractFetchOptions(input);
3307
- return request(
3351
+ return request2(
3308
3352
  {
3309
3353
  endpoint,
3310
3354
  method: "POST",
@@ -3316,7 +3360,7 @@ function createAuthClient(config = {}) {
3316
3360
  };
3317
3361
  const getGeneric = (endpoint, input, options) => {
3318
3362
  const { fetchOptions } = extractFetchOptions(input);
3319
- return request(
3363
+ return request2(
3320
3364
  {
3321
3365
  endpoint,
3322
3366
  method: "GET",
@@ -3328,7 +3372,7 @@ function createAuthClient(config = {}) {
3328
3372
  const getWithQuery = (endpoint, input, options) => {
3329
3373
  const { payload, fetchOptions } = extractFetchOptions(input);
3330
3374
  const query = payload?.query;
3331
- return request(
3375
+ return request2(
3332
3376
  {
3333
3377
  endpoint,
3334
3378
  method: "GET",
@@ -3346,18 +3390,19 @@ function createAuthClient(config = {}) {
3346
3390
  htmlField: "htmlBody",
3347
3391
  textField: "textBody"
3348
3392
  }, withReactEmailRoute(route));
3349
- const resolveAdminEmailTemplatePayload = (route, input) => resolveReactEmailPayloadFields(input, {
3393
+ const resolveAdminEmailTemplatePayload = (route, input) => resolveReactEmailPayloadFields(toReactEmailTemplateCompatibilityInput(input), {
3350
3394
  htmlField: "htmlTemplate",
3351
3395
  textField: "textTemplate",
3352
3396
  variablesField: "variables"
3353
3397
  }, withReactEmailRoute(route)).then((payload) => {
3398
+ const normalizedPayload = normalizeAdminEmailTemplatePayload(payload);
3354
3399
  if ("variables" in payload && payload.variables !== void 0 && payload.variables !== null) {
3355
3400
  assertAthenaAuthTemplateVariables(
3356
3401
  payload.variables,
3357
3402
  `${route} variables`
3358
3403
  );
3359
3404
  }
3360
- return payload;
3405
+ return normalizedPayload;
3361
3406
  });
3362
3407
  const requireSession = async (input, options) => {
3363
3408
  const sessionInput = input?.fetchOptions ? { fetchOptions: input.fetchOptions } : void 0;
@@ -3933,7 +3978,15 @@ function createAuthClient(config = {}) {
3933
3978
  await resolveAdminEmailTemplatePayload("/admin/email-template/update", input),
3934
3979
  options
3935
3980
  ),
3936
- delete: (input, options) => postGeneric("/admin/email-template/delete", input, options)
3981
+ delete: (input, options) => postGeneric("/admin/email-template/delete", input, options),
3982
+ send: (input, options) => postGeneric(
3983
+ "/admin/email-template/send",
3984
+ normalizeAdminEmailTemplateSendPayload(extractFetchOptions(input).payload),
3985
+ options
3986
+ )
3987
+ },
3988
+ eventType: {
3989
+ list: (input, options) => getWithQuery("/admin/email-event-type/list", input, options)
3937
3990
  }
3938
3991
  },
3939
3992
  emailTemplate: {
@@ -3949,7 +4002,15 @@ function createAuthClient(config = {}) {
3949
4002
  "/admin/email-template/update",
3950
4003
  await resolveAdminEmailTemplatePayload("/admin/email-template/update", input),
3951
4004
  options
4005
+ ),
4006
+ send: (input, options) => postGeneric(
4007
+ "/admin/email-template/send",
4008
+ normalizeAdminEmailTemplateSendPayload(extractFetchOptions(input).payload),
4009
+ options
3952
4010
  )
4011
+ },
4012
+ emailEventType: {
4013
+ list: (input, options) => getWithQuery("/admin/email-event-type/list", input, options)
3953
4014
  }
3954
4015
  },
3955
4016
  apiKey: {
@@ -3989,7 +4050,7 @@ function createAuthClient(config = {}) {
3989
4050
  throw new Error("callback.provider requires non-empty code and state values");
3990
4051
  }
3991
4052
  const endpoint = `/callback/${encodeURIComponent(provider)}`;
3992
- return request({
4053
+ return request2({
3993
4054
  endpoint,
3994
4055
  method: "GET",
3995
4056
  query: {
@@ -4003,7 +4064,7 @@ function createAuthClient(config = {}) {
4003
4064
  };
4004
4065
  return {
4005
4066
  baseUrl: normalizedBaseUrl,
4006
- request,
4067
+ request: request2,
4007
4068
  signIn: {
4008
4069
  email: (input, options) => executePostWithCompatibleInput(
4009
4070
  resolvedConfig,
@@ -4205,16 +4266,16 @@ function createStorageFileModule(base, config = {}) {
4205
4266
  };
4206
4267
  });
4207
4268
  input.onProgress?.(createProgressSnapshot("preparing", sources, 0, 0, 0));
4208
- const uploadUrls = uploadRequests.length === 1 ? [await base.createStorageUploadUrl(uploadRequests[0].uploadRequest, options)] : (await base.createStorageUploadUrls({ files: uploadRequests.map((request) => request.uploadRequest) }, options)).files;
4269
+ const uploadUrls = uploadRequests.length === 1 ? [await base.createStorageUploadUrl(uploadRequests[0].uploadRequest, options)] : (await base.createStorageUploadUrls({ files: uploadRequests.map((request2) => request2.uploadRequest) }, options)).files;
4209
4270
  const aggregateLoaded = new Array(uploadRequests.length).fill(0);
4210
4271
  const uploaded = [];
4211
4272
  for (let index = 0; index < uploadRequests.length; index += 1) {
4212
- const request = uploadRequests[index];
4273
+ const request2 = uploadRequests[index];
4213
4274
  const uploadUrl = uploadUrls[index];
4214
4275
  const response = await putUploadBody(
4215
4276
  uploadUrl.upload.url,
4216
4277
  uploadUrl.upload.headers ?? {},
4217
- request.source,
4278
+ request2.source,
4218
4279
  input,
4219
4280
  options,
4220
4281
  (progress) => {
@@ -4225,13 +4286,13 @@ function createStorageFileModule(base, config = {}) {
4225
4286
  uploaded.push({
4226
4287
  file: uploadUrl.file,
4227
4288
  upload: uploadUrl.upload,
4228
- source: request.source.source,
4229
- fileName: request.source.fileName,
4230
- storage_key: request.uploadRequest.storage_key,
4289
+ source: request2.source.source,
4290
+ fileName: request2.source.fileName,
4291
+ storage_key: request2.uploadRequest.storage_key,
4231
4292
  response
4232
4293
  });
4233
- aggregateLoaded[index] = request.source.sizeBytes;
4234
- input.onProgress?.(createProgressSnapshot("complete", sources, index, request.source.sizeBytes, sum(aggregateLoaded)));
4294
+ aggregateLoaded[index] = request2.source.sizeBytes;
4295
+ input.onProgress?.(createProgressSnapshot("complete", sources, index, request2.source.sizeBytes, sum(aggregateLoaded)));
4235
4296
  }
4236
4297
  return {
4237
4298
  files: uploaded,
@@ -6192,6 +6253,484 @@ function createStorageModule(gateway, runtimeOptions) {
6192
6253
  };
6193
6254
  }
6194
6255
 
6256
+ // src/chat/module.ts
6257
+ var SDK_NAME3 = "xylex-group/athena-chat";
6258
+ var SDK_HEADER_VALUE3 = buildSdkHeaderValue(SDK_NAME3);
6259
+ var NO_CACHE_HEADER_VALUE3 = "no-cache";
6260
+ var AthenaChatError = class extends Error {
6261
+ status;
6262
+ endpoint;
6263
+ method;
6264
+ requestId;
6265
+ body;
6266
+ constructor(input) {
6267
+ super(input.message);
6268
+ this.name = "AthenaChatError";
6269
+ this.status = input.status;
6270
+ this.endpoint = input.endpoint;
6271
+ this.method = input.method;
6272
+ this.requestId = input.requestId;
6273
+ this.body = input.body;
6274
+ }
6275
+ };
6276
+ function deriveRealtimeInfoUrl(wsUrl) {
6277
+ if (!wsUrl) {
6278
+ return void 0;
6279
+ }
6280
+ const parsed = new URL(normalizeWsUrl(wsUrl, "Athena chat WebSocket URL"));
6281
+ parsed.protocol = parsed.protocol === "wss:" ? "https:" : "http:";
6282
+ parsed.pathname = parsed.pathname.replace(/\/wss\/gateway$/, "/wss/info");
6283
+ return parsed.toString();
6284
+ }
6285
+ function normalizeWsUrl(value, label) {
6286
+ const normalized = value.trim();
6287
+ if (!normalized) {
6288
+ throw new Error(`${label} is required.`);
6289
+ }
6290
+ let parsed;
6291
+ try {
6292
+ parsed = new URL(normalized);
6293
+ } catch {
6294
+ throw new Error(`${label} must be a valid absolute ws(s) URL.`);
6295
+ }
6296
+ if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") {
6297
+ throw new Error(`${label} must use ws or wss.`);
6298
+ }
6299
+ parsed.pathname = parsed.pathname.replace(/\/+$/, "");
6300
+ return parsed.toString().replace(/\/$/, "");
6301
+ }
6302
+ function isRecord7(value) {
6303
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6304
+ }
6305
+ function normalizeHeaderValue3(value) {
6306
+ return value ? value : void 0;
6307
+ }
6308
+ function parseResponseBody4(rawText, contentType) {
6309
+ if (!rawText) {
6310
+ return { parsed: null, parseFailed: false };
6311
+ }
6312
+ const contentTypeSuggestsJson = contentType?.toLowerCase().includes("application/json") ?? false;
6313
+ const looksJson = contentTypeSuggestsJson || rawText.startsWith("{") || rawText.startsWith("[");
6314
+ if (!looksJson) {
6315
+ return { parsed: rawText, parseFailed: false };
6316
+ }
6317
+ try {
6318
+ return { parsed: JSON.parse(rawText), parseFailed: false };
6319
+ } catch {
6320
+ return { parsed: rawText, parseFailed: true };
6321
+ }
6322
+ }
6323
+ function resolveRequestId3(headers) {
6324
+ return headers.get("x-request-id") ?? headers.get("x-correlation-id") ?? headers.get("x-athena-request-id") ?? void 0;
6325
+ }
6326
+ function resolveErrorMessage4(payload, fallback) {
6327
+ if (isRecord7(payload)) {
6328
+ for (const candidate of [payload.error, payload.message, payload.details]) {
6329
+ if (typeof candidate === "string" && candidate.trim().length > 0) {
6330
+ return candidate.trim();
6331
+ }
6332
+ }
6333
+ }
6334
+ if (typeof payload === "string" && payload.trim().length > 0) {
6335
+ return payload.trim();
6336
+ }
6337
+ return fallback;
6338
+ }
6339
+ function encodePathSegment(value, label) {
6340
+ const normalized = value.trim();
6341
+ if (!normalized) {
6342
+ throw new Error(`${label} is required.`);
6343
+ }
6344
+ return encodeURIComponent(normalized);
6345
+ }
6346
+ function encodeQuery(query) {
6347
+ if (!query) {
6348
+ return "";
6349
+ }
6350
+ const params = new URLSearchParams();
6351
+ for (const [key, value] of Object.entries(query)) {
6352
+ if (value === void 0 || value === null) {
6353
+ continue;
6354
+ }
6355
+ if (Array.isArray(value)) {
6356
+ for (const item of value) {
6357
+ if (item !== void 0 && item !== null) {
6358
+ params.append(key, String(item));
6359
+ }
6360
+ }
6361
+ continue;
6362
+ }
6363
+ params.set(key, String(value));
6364
+ }
6365
+ const encoded = params.toString();
6366
+ return encoded ? `?${encoded}` : "";
6367
+ }
6368
+ function createSocket(factory, url, protocols) {
6369
+ try {
6370
+ return new factory(url, protocols);
6371
+ } catch (error) {
6372
+ if (error instanceof TypeError) {
6373
+ return factory(url, protocols);
6374
+ }
6375
+ throw error;
6376
+ }
6377
+ }
6378
+ function buildHeaders3(config, options) {
6379
+ const headers = {
6380
+ Accept: "application/json",
6381
+ apikey: config.apiKey,
6382
+ "x-api-key": config.apiKey,
6383
+ "X-Athena-Sdk": SDK_HEADER_VALUE3
6384
+ };
6385
+ if (config.client || options?.client) {
6386
+ headers["X-Athena-Client"] = options?.client ?? config.client ?? "";
6387
+ }
6388
+ const bearerToken = options?.bearerToken ?? config.bearerToken;
6389
+ if (typeof bearerToken === "string" && bearerToken.trim()) {
6390
+ headers.Authorization = bearerToken.startsWith("Bearer ") ? bearerToken : `Bearer ${bearerToken}`;
6391
+ }
6392
+ const cookie = options?.cookie ?? config.cookie;
6393
+ if (typeof cookie === "string" && cookie.trim()) {
6394
+ headers.Cookie = cookie;
6395
+ }
6396
+ const sessionToken = options?.sessionToken ?? config.sessionToken;
6397
+ if (typeof sessionToken === "string" && sessionToken.trim()) {
6398
+ headers["X-Athena-Auth-Session-Token"] = sessionToken;
6399
+ }
6400
+ if (config.forceNoCache || options?.forceNoCache) {
6401
+ headers["Cache-Control"] = NO_CACHE_HEADER_VALUE3;
6402
+ }
6403
+ for (const source of [config.headers, options?.headers]) {
6404
+ for (const [key, value] of Object.entries(source ?? {})) {
6405
+ const normalized = normalizeHeaderValue3(value);
6406
+ if (normalized) {
6407
+ headers[key] = normalized;
6408
+ }
6409
+ }
6410
+ }
6411
+ return headers;
6412
+ }
6413
+ function withJsonBody(init, body) {
6414
+ return {
6415
+ ...init,
6416
+ body: body === void 0 ? void 0 : JSON.stringify(body),
6417
+ headers: {
6418
+ "Content-Type": "application/json",
6419
+ ...init.headers
6420
+ }
6421
+ };
6422
+ }
6423
+ async function request(config, method, endpoint, options, body) {
6424
+ if (!config.baseUrl) {
6425
+ throw new Error(
6426
+ "Athena chat base URL is not configured. Pass createClient({ url }) for unified routing or set chat.url / chatUrl explicitly."
6427
+ );
6428
+ }
6429
+ const url = `${config.baseUrl}${endpoint}`;
6430
+ const init = {
6431
+ method,
6432
+ headers: buildHeaders3(config, options),
6433
+ signal: options?.signal
6434
+ };
6435
+ const finalInit = body === void 0 || method === "GET" ? init : withJsonBody(init, body);
6436
+ const response = await fetch(url, finalInit);
6437
+ const rawText = await response.text();
6438
+ const { parsed } = parseResponseBody4(rawText, response.headers.get("content-type"));
6439
+ if (!response.ok) {
6440
+ throw new AthenaChatError({
6441
+ message: resolveErrorMessage4(parsed, `Athena chat ${method} ${endpoint} failed with ${response.status}`),
6442
+ status: response.status,
6443
+ endpoint,
6444
+ method,
6445
+ requestId: resolveRequestId3(response.headers),
6446
+ body: parsed
6447
+ });
6448
+ }
6449
+ return parsed;
6450
+ }
6451
+ function createRealtimeConnection(config, options) {
6452
+ if (!config.wsUrl) {
6453
+ throw new Error(
6454
+ "Athena chat WebSocket URL is not configured. Pass createClient({ url }) for unified routing or set chat.wsUrl / chatWsUrl explicitly."
6455
+ );
6456
+ }
6457
+ const wsFactory = config.webSocketFactory ?? globalThis.WebSocket;
6458
+ if (!wsFactory) {
6459
+ throw new Error(
6460
+ "No WebSocket implementation is available. Provide chat.webSocketFactory in createClient(...) or run in a runtime with global WebSocket support."
6461
+ );
6462
+ }
6463
+ const socket = createSocket(wsFactory, config.wsUrl, options?.protocols);
6464
+ const send = (command) => {
6465
+ socket.send(JSON.stringify(command));
6466
+ };
6467
+ if (options?.onMessage) {
6468
+ const listener = (event) => {
6469
+ const messageEvent = event;
6470
+ const raw = messageEvent?.data;
6471
+ if (typeof raw !== "string") {
6472
+ return;
6473
+ }
6474
+ try {
6475
+ options.onMessage?.(JSON.parse(raw));
6476
+ } catch {
6477
+ options.onMessage?.({ type: "error", error: "Invalid JSON message from Athena chat realtime gateway." });
6478
+ }
6479
+ };
6480
+ if (typeof socket.addEventListener === "function") {
6481
+ socket.addEventListener("message", listener);
6482
+ } else {
6483
+ socket.onmessage = listener;
6484
+ }
6485
+ }
6486
+ const hello = (command) => {
6487
+ send({
6488
+ type: "auth.hello",
6489
+ token: command?.token,
6490
+ room_subscriptions: command?.room_subscriptions
6491
+ });
6492
+ };
6493
+ if (options?.hello) {
6494
+ const onOpen = () => hello({
6495
+ token: options.hello?.token ?? void 0,
6496
+ room_subscriptions: options.hello?.room_subscriptions ?? void 0
6497
+ });
6498
+ if (typeof socket.addEventListener === "function") {
6499
+ socket.addEventListener("open", onOpen);
6500
+ } else {
6501
+ socket.onopen = onOpen;
6502
+ }
6503
+ }
6504
+ return {
6505
+ socket,
6506
+ send,
6507
+ hello,
6508
+ subscribe(roomId, fromSeq) {
6509
+ send({
6510
+ type: "chat.subscribe",
6511
+ room_id: roomId,
6512
+ from_seq: fromSeq ?? void 0
6513
+ });
6514
+ },
6515
+ unsubscribe(roomId) {
6516
+ send({
6517
+ type: "chat.unsubscribe",
6518
+ room_id: roomId
6519
+ });
6520
+ },
6521
+ resume(rooms) {
6522
+ send({
6523
+ type: "chat.resume",
6524
+ rooms
6525
+ });
6526
+ },
6527
+ typingStart(roomId) {
6528
+ send({
6529
+ type: "chat.typing.start",
6530
+ room_id: roomId
6531
+ });
6532
+ },
6533
+ typingStop(roomId) {
6534
+ send({
6535
+ type: "chat.typing.stop",
6536
+ room_id: roomId
6537
+ });
6538
+ },
6539
+ presenceHeartbeat(activeRoomId) {
6540
+ send({
6541
+ type: "chat.presence.heartbeat",
6542
+ active_room_id: activeRoomId ?? void 0
6543
+ });
6544
+ },
6545
+ readUpTo(roomId, input) {
6546
+ send({
6547
+ type: "chat.read.up_to",
6548
+ room_id: roomId,
6549
+ message_id: input?.message_id ?? void 0,
6550
+ seq: input?.seq ?? void 0
6551
+ });
6552
+ },
6553
+ ping(at = (/* @__PURE__ */ new Date()).toISOString()) {
6554
+ send({
6555
+ type: "ping",
6556
+ at
6557
+ });
6558
+ },
6559
+ close(code, reason) {
6560
+ socket.close(code, reason);
6561
+ }
6562
+ };
6563
+ }
6564
+ function createChatModule(config) {
6565
+ const realtime = {
6566
+ info(options) {
6567
+ const realtimeInfoUrl = config.realtimeInfoUrl ?? deriveRealtimeInfoUrl(config.wsUrl);
6568
+ if (!realtimeInfoUrl) {
6569
+ throw new Error(
6570
+ "Athena chat realtime info URL is not configured. Pass createClient({ url }) for unified routing or set chat.wsUrl / chatWsUrl explicitly."
6571
+ );
6572
+ }
6573
+ return request(
6574
+ {
6575
+ ...config,
6576
+ baseUrl: realtimeInfoUrl
6577
+ },
6578
+ "GET",
6579
+ "",
6580
+ options
6581
+ );
6582
+ },
6583
+ connect(options) {
6584
+ return createRealtimeConnection(config, options);
6585
+ }
6586
+ };
6587
+ return {
6588
+ room: {
6589
+ list(query, options) {
6590
+ return request(
6591
+ config,
6592
+ "GET",
6593
+ `/rooms${encodeQuery(query)}`,
6594
+ options
6595
+ );
6596
+ },
6597
+ create(input, options) {
6598
+ return request(config, "POST", "/rooms", options, input);
6599
+ },
6600
+ get(roomId, options) {
6601
+ return request(
6602
+ config,
6603
+ "GET",
6604
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}`,
6605
+ options
6606
+ );
6607
+ },
6608
+ update(roomId, input, options) {
6609
+ return request(
6610
+ config,
6611
+ "PATCH",
6612
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}`,
6613
+ options,
6614
+ input
6615
+ );
6616
+ },
6617
+ archive(roomId, options) {
6618
+ return request(
6619
+ config,
6620
+ "POST",
6621
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/archive`,
6622
+ options
6623
+ );
6624
+ },
6625
+ readCursor: {
6626
+ upTo(roomId, input, options) {
6627
+ return request(
6628
+ config,
6629
+ "POST",
6630
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/read-cursor`,
6631
+ options,
6632
+ input ?? {}
6633
+ );
6634
+ }
6635
+ },
6636
+ member: {
6637
+ list(roomId, options) {
6638
+ return request(
6639
+ config,
6640
+ "GET",
6641
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/members`,
6642
+ options
6643
+ );
6644
+ },
6645
+ add(roomId, input, options) {
6646
+ return request(
6647
+ config,
6648
+ "POST",
6649
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/members`,
6650
+ options,
6651
+ input
6652
+ );
6653
+ },
6654
+ remove(roomId, userId, options) {
6655
+ return request(
6656
+ config,
6657
+ "DELETE",
6658
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/members/${encodePathSegment(userId, "chat user ID")}`,
6659
+ options
6660
+ );
6661
+ }
6662
+ },
6663
+ message: {
6664
+ list(roomId, query, options) {
6665
+ return request(
6666
+ config,
6667
+ "GET",
6668
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages${encodeQuery(query)}`,
6669
+ options
6670
+ );
6671
+ },
6672
+ send(roomId, input, options) {
6673
+ return request(
6674
+ config,
6675
+ "POST",
6676
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages`,
6677
+ options,
6678
+ input
6679
+ );
6680
+ },
6681
+ update(roomId, messageId, input, options) {
6682
+ return request(
6683
+ config,
6684
+ "PATCH",
6685
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages/${encodePathSegment(messageId, "chat message ID")}`,
6686
+ options,
6687
+ input
6688
+ );
6689
+ },
6690
+ delete(roomId, messageId, options) {
6691
+ return request(
6692
+ config,
6693
+ "DELETE",
6694
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages/${encodePathSegment(messageId, "chat message ID")}`,
6695
+ options
6696
+ );
6697
+ }
6698
+ }
6699
+ },
6700
+ message: {
6701
+ reaction: {
6702
+ add(messageId, input, options) {
6703
+ return request(
6704
+ config,
6705
+ "POST",
6706
+ `/messages/${encodePathSegment(messageId, "chat message ID")}/reactions`,
6707
+ options,
6708
+ input
6709
+ );
6710
+ },
6711
+ remove(messageId, emoji, options) {
6712
+ return request(
6713
+ config,
6714
+ "DELETE",
6715
+ `/messages/${encodePathSegment(messageId, "chat message ID")}/reactions/${encodePathSegment(emoji, "reaction emoji")}`,
6716
+ options
6717
+ );
6718
+ }
6719
+ },
6720
+ search(input, options) {
6721
+ return request(
6722
+ config,
6723
+ "POST",
6724
+ "/messages/search",
6725
+ options,
6726
+ input
6727
+ );
6728
+ }
6729
+ },
6730
+ realtime
6731
+ };
6732
+ }
6733
+
6195
6734
  // src/client-builder.ts
6196
6735
  var DEFAULT_BACKEND = { type: "athena" };
6197
6736
  function toBackendConfig(value) {
@@ -6226,7 +6765,7 @@ var BOOLEAN_SAFE_OPERATORS = /* @__PURE__ */ new Set([
6226
6765
  "ilike",
6227
6766
  "is"
6228
6767
  ]);
6229
- function isRecord7(value) {
6768
+ function isRecord8(value) {
6230
6769
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6231
6770
  }
6232
6771
  function isUuidString(value) {
@@ -6239,7 +6778,7 @@ function shouldUseUuidTextComparison(column, value) {
6239
6778
  return typeof value === "string" && isUuidString(value) && isUuidIdentifierColumn(column);
6240
6779
  }
6241
6780
  function isRelationSelectNode(value) {
6242
- return isRecord7(value) && isRecord7(value.select);
6781
+ return isRecord8(value) && isRecord8(value.select);
6243
6782
  }
6244
6783
  function normalizeIdentifier(value, label) {
6245
6784
  const normalized = value.trim();
@@ -6295,7 +6834,7 @@ function compileRelationToken(key, node) {
6295
6834
  return `${prefix}${relationToken}(${nested})`;
6296
6835
  }
6297
6836
  function compileSelectShape(select) {
6298
- if (!isRecord7(select)) {
6837
+ if (!isRecord8(select)) {
6299
6838
  throw new Error("findMany select must be an object");
6300
6839
  }
6301
6840
  const tokens = [];
@@ -6319,7 +6858,7 @@ function compileSelectShape(select) {
6319
6858
  return tokens.join(",");
6320
6859
  }
6321
6860
  function selectShapeUsesRelationSchema(select) {
6322
- if (!isRecord7(select)) {
6861
+ if (!isRecord8(select)) {
6323
6862
  return false;
6324
6863
  }
6325
6864
  for (const rawValue of Object.values(select)) {
@@ -6337,7 +6876,7 @@ function selectShapeUsesRelationSchema(select) {
6337
6876
  }
6338
6877
  function compileColumnWhere(column, input) {
6339
6878
  const normalizedColumn = normalizeIdentifier(column, "where column");
6340
- if (!isRecord7(input)) {
6879
+ if (!isRecord8(input)) {
6341
6880
  return [buildGatewayCondition("eq", normalizedColumn, input)];
6342
6881
  }
6343
6882
  const conditions = [];
@@ -6365,7 +6904,7 @@ function compileColumnWhere(column, input) {
6365
6904
  return conditions;
6366
6905
  }
6367
6906
  function compileBooleanExpressionTerms(clause, label) {
6368
- if (!isRecord7(clause)) {
6907
+ if (!isRecord8(clause)) {
6369
6908
  throw new Error(`findMany where.${label} clauses must be objects`);
6370
6909
  }
6371
6910
  const entries = Object.entries(clause).filter(([, value]) => value !== void 0);
@@ -6374,7 +6913,7 @@ function compileBooleanExpressionTerms(clause, label) {
6374
6913
  }
6375
6914
  const [rawColumn, rawValue] = entries[0];
6376
6915
  const column = normalizeIdentifier(rawColumn, `where.${label} column`);
6377
- if (!isRecord7(rawValue)) {
6916
+ if (!isRecord8(rawValue)) {
6378
6917
  return [`${column}.eq.${stringifyFilterValue(rawValue)}`];
6379
6918
  }
6380
6919
  const operatorEntries = Object.entries(rawValue).filter(([, value]) => value !== void 0);
@@ -6398,7 +6937,7 @@ function compileWhere(where) {
6398
6937
  if (where === void 0) {
6399
6938
  return void 0;
6400
6939
  }
6401
- if (!isRecord7(where)) {
6940
+ if (!isRecord8(where)) {
6402
6941
  throw new Error("findMany where must be an object");
6403
6942
  }
6404
6943
  const conditions = [];
@@ -6448,7 +6987,7 @@ function compileOrderBy(orderBy) {
6448
6987
  if (orderBy === void 0) {
6449
6988
  return void 0;
6450
6989
  }
6451
- if (!isRecord7(orderBy)) {
6990
+ if (!isRecord8(orderBy)) {
6452
6991
  throw new Error("findMany orderBy must be an object");
6453
6992
  }
6454
6993
  if ("column" in orderBy) {
@@ -6623,11 +7162,11 @@ function toFindManyAstOrder(order) {
6623
7162
  ascending: order.direction !== "descending"
6624
7163
  };
6625
7164
  }
6626
- function isRecord8(value) {
7165
+ function isRecord9(value) {
6627
7166
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6628
7167
  }
6629
7168
  function normalizeFindManyAstColumnPredicate(value) {
6630
- if (!isRecord8(value)) {
7169
+ if (!isRecord9(value)) {
6631
7170
  return {
6632
7171
  eq: value
6633
7172
  };
@@ -6651,7 +7190,7 @@ function normalizeFindManyAstBooleanOperand(clause) {
6651
7190
  return normalized;
6652
7191
  }
6653
7192
  function normalizeFindManyAstWhere(where) {
6654
- if (!where || !isRecord8(where)) {
7193
+ if (!where || !isRecord9(where)) {
6655
7194
  return where;
6656
7195
  }
6657
7196
  const normalized = {};
@@ -6665,7 +7204,7 @@ function normalizeFindManyAstWhere(where) {
6665
7204
  );
6666
7205
  continue;
6667
7206
  }
6668
- if (key === "not" && isRecord8(value)) {
7207
+ if (key === "not" && isRecord9(value)) {
6669
7208
  normalized.not = normalizeFindManyAstBooleanOperand(
6670
7209
  value
6671
7210
  );
@@ -6676,7 +7215,7 @@ function normalizeFindManyAstWhere(where) {
6676
7215
  return normalized;
6677
7216
  }
6678
7217
  function predicateRequiresUuidQueryFallback(column, value) {
6679
- if (!isRecord8(value)) {
7218
+ if (!isRecord9(value)) {
6680
7219
  return shouldUseUuidTextComparison(column, value);
6681
7220
  }
6682
7221
  const eqValue = value.eq;
@@ -6694,7 +7233,7 @@ function booleanOperandRequiresUuidQueryFallback(clause) {
6694
7233
  return false;
6695
7234
  }
6696
7235
  function findManyAstWhereRequiresLegacyTransport(where) {
6697
- if (!where || !isRecord8(where)) {
7236
+ if (!where || !isRecord9(where)) {
6698
7237
  return false;
6699
7238
  }
6700
7239
  for (const [key, value] of Object.entries(where)) {
@@ -6709,7 +7248,7 @@ function findManyAstWhereRequiresLegacyTransport(where) {
6709
7248
  }
6710
7249
  continue;
6711
7250
  }
6712
- if (key === "not" && isRecord8(value)) {
7251
+ if (key === "not" && isRecord9(value)) {
6713
7252
  if (booleanOperandRequiresUuidQueryFallback(value)) {
6714
7253
  return true;
6715
7254
  }
@@ -7252,6 +7791,7 @@ function resolveAthenaModelTargetTableName(target, options = {}) {
7252
7791
  var DEFAULT_COLUMNS = "*";
7253
7792
  var SAFE_CAST_PATTERN = /^[a-z_][a-z0-9_]*(?:\[\])?$/i;
7254
7793
  var ATHENA_NORMALIZED_ERROR_KEY = "__athenaNormalizedError";
7794
+ var SDK_NAME4 = "xylex-group/athena";
7255
7795
  function formatResult(response) {
7256
7796
  const result = {
7257
7797
  data: response.data ?? null,
@@ -7328,7 +7868,7 @@ async function executeExperimentalRead(experimental, runner) {
7328
7868
  throw error;
7329
7869
  }
7330
7870
  }
7331
- function isRecord9(value) {
7871
+ function isRecord10(value) {
7332
7872
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
7333
7873
  }
7334
7874
  function firstNonEmptyString2(...values) {
@@ -7340,8 +7880,8 @@ function firstNonEmptyString2(...values) {
7340
7880
  return void 0;
7341
7881
  }
7342
7882
  function resolveStructuredErrorPayload2(raw) {
7343
- if (!isRecord9(raw)) return null;
7344
- return isRecord9(raw.error) ? raw.error : raw;
7883
+ if (!isRecord10(raw)) return null;
7884
+ return isRecord10(raw.error) ? raw.error : raw;
7345
7885
  }
7346
7886
  function resolveStructuredErrorDetails(payload, message) {
7347
7887
  if (!payload || !("details" in payload)) {
@@ -7357,7 +7897,7 @@ function resolveStructuredErrorDetails(payload, message) {
7357
7897
  return details;
7358
7898
  }
7359
7899
  function createResultError(response, result, normalized) {
7360
- const rawRecord = isRecord9(response.raw) ? response.raw : null;
7900
+ const rawRecord = isRecord10(response.raw) ? response.raw : null;
7361
7901
  const payload = resolveStructuredErrorPayload2(response.raw);
7362
7902
  const message = firstNonEmptyString2(
7363
7903
  response.error,
@@ -7420,6 +7960,43 @@ function asAthenaJsonObject(value) {
7420
7960
  function asAthenaJsonObjectArray(values) {
7421
7961
  return values;
7422
7962
  }
7963
+ function parseArbitraryResponseBody(rawText, contentType) {
7964
+ if (!rawText) {
7965
+ return null;
7966
+ }
7967
+ const contentTypeSuggestsJson = contentType?.toLowerCase().includes("application/json") ?? false;
7968
+ const looksJson = contentTypeSuggestsJson || rawText.startsWith("{") || rawText.startsWith("[");
7969
+ if (!looksJson) {
7970
+ return rawText;
7971
+ }
7972
+ try {
7973
+ return JSON.parse(rawText);
7974
+ } catch {
7975
+ return rawText;
7976
+ }
7977
+ }
7978
+ function toRequestQueryString(query) {
7979
+ if (!query) {
7980
+ return "";
7981
+ }
7982
+ const params = new URLSearchParams();
7983
+ for (const [key, value] of Object.entries(query)) {
7984
+ if (value === void 0 || value === null) {
7985
+ continue;
7986
+ }
7987
+ if (Array.isArray(value)) {
7988
+ for (const item of value) {
7989
+ if (item !== void 0 && item !== null) {
7990
+ params.append(key, String(item));
7991
+ }
7992
+ }
7993
+ continue;
7994
+ }
7995
+ params.set(key, String(value));
7996
+ }
7997
+ const encoded = params.toString();
7998
+ return encoded ? `?${encoded}` : "";
7999
+ }
7423
8000
  function normalizeSelectColumnsInput(columns) {
7424
8001
  if (columns === void 0) {
7425
8002
  return void 0;
@@ -8782,6 +9359,15 @@ function appendServicePath(baseUrl, segment) {
8782
9359
  const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(baseUrl, { label: "Athena public base URL" });
8783
9360
  return `${normalizedBaseUrl}/${segment.replace(/^\/+/, "")}`;
8784
9361
  }
9362
+ function appendRealtimeGatewayPath(baseUrl) {
9363
+ const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(baseUrl, { label: "Athena public base URL" });
9364
+ const wsUrl = new URL(normalizedBaseUrl);
9365
+ wsUrl.protocol = wsUrl.protocol === "https:" ? "wss:" : "ws:";
9366
+ wsUrl.pathname = `${wsUrl.pathname.replace(/\/+$/, "")}/wss/gateway`;
9367
+ wsUrl.search = "";
9368
+ wsUrl.hash = "";
9369
+ return wsUrl.toString();
9370
+ }
8785
9371
  function resolveServiceUrlOverride(value, label) {
8786
9372
  return resolveClientServiceBaseUrl(value, label);
8787
9373
  }
@@ -8790,6 +9376,8 @@ function resolveServiceUrls(config) {
8790
9376
  return {
8791
9377
  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),
8792
9378
  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),
9379
+ chatUrl: resolveServiceUrlOverride(config.chat?.url, "Athena chat base URL") ?? resolveServiceUrlOverride(config.chatUrl, "Athena chat base URL") ?? (baseUrl ? appendServicePath(baseUrl, "chat") : void 0),
9380
+ chatWsUrl: normalizeOptionalString2(config.chat?.wsUrl) ?? normalizeOptionalString2(config.chatWsUrl) ?? (baseUrl ? appendRealtimeGatewayPath(baseUrl) : void 0),
8793
9381
  storageUrl: resolveServiceUrlOverride(config.storage?.url, "Athena storage base URL") ?? resolveServiceUrlOverride(config.storageUrl, "Athena storage base URL") ?? (baseUrl ? appendServicePath(baseUrl, "storage") : void 0)
8794
9382
  };
8795
9383
  }
@@ -8882,6 +9470,7 @@ function mergeClientOverrideOptions(base, overrides) {
8882
9470
  } : void 0,
8883
9471
  db: base.db ? { ...base.db } : void 0,
8884
9472
  gateway: base.gateway ? { ...base.gateway } : void 0,
9473
+ chat: base.chat ? { ...base.chat } : void 0,
8885
9474
  storage: base.storage ? { ...base.storage } : void 0
8886
9475
  };
8887
9476
  }
@@ -8892,6 +9481,7 @@ function mergeClientOverrideOptions(base, overrides) {
8892
9481
  auth: mergeAuthClientOptions(base.auth, overrides.auth),
8893
9482
  db: mergeServiceUrlOverrides(base.db, overrides.db),
8894
9483
  gateway: mergeServiceUrlOverrides(base.gateway, overrides.gateway),
9484
+ chat: mergeServiceUrlOverrides(base.chat, overrides.chat),
8895
9485
  storage: mergeServiceUrlOverrides(base.storage, overrides.storage)
8896
9486
  };
8897
9487
  }
@@ -8950,6 +9540,9 @@ function resolveCreateClientConfig(config) {
8950
9540
  headers: config.headers,
8951
9541
  auth: config.auth,
8952
9542
  authUrl: resolvedUrls.authUrl,
9543
+ chat: config.chat,
9544
+ chatUrl: resolvedUrls.chatUrl,
9545
+ chatWsUrl: resolvedUrls.chatWsUrl,
8953
9546
  storageUrl: resolvedUrls.storageUrl,
8954
9547
  experimental: config.experimental
8955
9548
  };
@@ -9034,6 +9627,119 @@ function createClientFromConfig(config, sourceConfig) {
9034
9627
  queryTracer
9035
9628
  );
9036
9629
  const db = createDbModule({ from, rpc, query });
9630
+ const chat = createChatModule({
9631
+ baseUrl: config.chatUrl,
9632
+ apiKey: config.apiKey,
9633
+ client: config.client,
9634
+ headers: config.headers,
9635
+ bearerToken: normalizedAuthConfig?.bearerToken,
9636
+ cookie: normalizedAuthConfig?.cookie,
9637
+ sessionToken: normalizedAuthConfig?.sessionToken,
9638
+ forceNoCache: config.forceNoCache,
9639
+ wsUrl: config.chatWsUrl,
9640
+ webSocketFactory: config.chat?.webSocketFactory ?? void 0
9641
+ });
9642
+ const request2 = async (options) => {
9643
+ const method = options.method ?? "GET";
9644
+ const responseType = options.responseType ?? "json";
9645
+ const service = options.service ?? "db";
9646
+ const baseUrlByService = {
9647
+ db: config.baseUrl,
9648
+ auth: config.authUrl,
9649
+ chat: config.chatUrl,
9650
+ storage: config.storageUrl
9651
+ };
9652
+ const resolvedBaseUrl = options.url ?? baseUrlByService[service];
9653
+ if (!resolvedBaseUrl) {
9654
+ throw new Error(
9655
+ `Athena ${service} base URL is not configured. Pass createClient({ url }) for unified routing or set the service-specific URL first.`
9656
+ );
9657
+ }
9658
+ const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(resolvedBaseUrl, {
9659
+ label: `Athena ${service} base URL`
9660
+ });
9661
+ const normalizedPath = options.url ? "" : (() => {
9662
+ const path = options.path?.trim();
9663
+ if (!path) {
9664
+ throw new Error("client.request(...) requires either an absolute url or a non-empty path.");
9665
+ }
9666
+ return path.startsWith("/") ? path : `/${path}`;
9667
+ })();
9668
+ const targetUrl = options.url ? `${normalizedBaseUrl}${toRequestQueryString(options.query)}` : `${normalizedBaseUrl}${normalizedPath}${toRequestQueryString(options.query)}`;
9669
+ const headers = {
9670
+ "X-Athena-Sdk": buildSdkHeaderValue(SDK_NAME4),
9671
+ ...config.headers ?? {},
9672
+ ...options.headers ?? {}
9673
+ };
9674
+ if (service !== "auth") {
9675
+ headers.apikey = headers.apikey ?? config.apiKey;
9676
+ headers["x-api-key"] = headers["x-api-key"] ?? config.apiKey;
9677
+ if (config.client && !hasHeaderIgnoreCase(headers, "X-Athena-Client")) {
9678
+ headers["X-Athena-Client"] = config.client;
9679
+ }
9680
+ if (config.userId && !hasHeaderIgnoreCase(headers, "X-User-Id")) {
9681
+ headers["X-User-Id"] = config.userId;
9682
+ }
9683
+ if (config.organizationId && !hasHeaderIgnoreCase(headers, "X-Organization-Id")) {
9684
+ headers["X-Organization-Id"] = config.organizationId;
9685
+ }
9686
+ if (normalizedAuthConfig?.sessionToken && !hasHeaderIgnoreCase(headers, "X-Athena-Auth-Session-Token")) {
9687
+ headers["X-Athena-Auth-Session-Token"] = normalizedAuthConfig.sessionToken;
9688
+ }
9689
+ if (normalizedAuthConfig?.bearerToken && !hasHeaderIgnoreCase(headers, "X-Athena-Auth-Bearer-Token")) {
9690
+ headers["X-Athena-Auth-Bearer-Token"] = normalizedAuthConfig.bearerToken;
9691
+ }
9692
+ if (normalizedAuthConfig?.cookie && !hasHeaderIgnoreCase(headers, "Cookie")) {
9693
+ headers.Cookie = normalizedAuthConfig.cookie;
9694
+ }
9695
+ } else {
9696
+ const authApiKey = normalizedAuthConfig?.apiKey ?? config.apiKey;
9697
+ if (authApiKey && !hasHeaderIgnoreCase(headers, "x-api-key")) {
9698
+ headers.apikey = headers.apikey ?? authApiKey;
9699
+ headers["x-api-key"] = headers["x-api-key"] ?? authApiKey;
9700
+ }
9701
+ if (normalizedAuthConfig?.bearerToken && !hasHeaderIgnoreCase(headers, "Authorization")) {
9702
+ headers.Authorization = `Bearer ${normalizedAuthConfig.bearerToken}`;
9703
+ }
9704
+ if (normalizedAuthConfig?.cookie && !hasHeaderIgnoreCase(headers, "Cookie")) {
9705
+ headers.Cookie = normalizedAuthConfig.cookie;
9706
+ }
9707
+ if (normalizedAuthConfig?.sessionToken && !hasHeaderIgnoreCase(headers, "X-Athena-Auth-Session-Token")) {
9708
+ headers["X-Athena-Auth-Session-Token"] = normalizedAuthConfig.sessionToken;
9709
+ }
9710
+ }
9711
+ 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";
9712
+ if (shouldSendJsonBody && !hasHeaderIgnoreCase(headers, "Content-Type")) {
9713
+ headers["Content-Type"] = "application/json";
9714
+ }
9715
+ const response = await fetch(targetUrl, {
9716
+ method,
9717
+ headers,
9718
+ body: options.body === void 0 || options.body === null ? void 0 : shouldSendJsonBody ? JSON.stringify(options.body) : options.body,
9719
+ signal: options.signal,
9720
+ credentials: options.credentials
9721
+ });
9722
+ if (responseType === "response") {
9723
+ return {
9724
+ ok: response.ok,
9725
+ status: response.status,
9726
+ statusText: response.statusText,
9727
+ headers: response.headers,
9728
+ data: null,
9729
+ raw: response
9730
+ };
9731
+ }
9732
+ const rawText = await response.text();
9733
+ const parsed = responseType === "text" ? rawText : parseArbitraryResponseBody(rawText, response.headers.get("content-type"));
9734
+ return {
9735
+ ok: response.ok,
9736
+ status: response.status,
9737
+ statusText: response.statusText,
9738
+ headers: response.headers,
9739
+ data: parsed,
9740
+ raw: response
9741
+ };
9742
+ };
9037
9743
  const withContext = (context) => createClientFromInput(
9038
9744
  mergeClientOverrideOptions(sourceConfig, toClientContextOverrides(context))
9039
9745
  );
@@ -9049,8 +9755,10 @@ function createClientFromConfig(config, sourceConfig) {
9049
9755
  db,
9050
9756
  rpc,
9051
9757
  query,
9758
+ request: request2,
9052
9759
  verifyConnection: gateway.verifyConnection,
9053
9760
  auth: auth.auth,
9761
+ chat,
9054
9762
  withContext,
9055
9763
  withSession,
9056
9764
  withOptions: authWithOptions