@xylex-group/athena 2.8.2 → 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 (52) hide show
  1. package/README.md +154 -64
  2. package/dist/browser.cjs +1550 -181
  3. package/dist/browser.cjs.map +1 -1
  4. package/dist/browser.d.cts +8 -7
  5. package/dist/browser.d.ts +8 -7
  6. package/dist/browser.js +1540 -182
  7. package/dist/browser.js.map +1 -1
  8. package/dist/cli/index.cjs +1337 -67
  9. package/dist/cli/index.cjs.map +1 -1
  10. package/dist/cli/index.d.cts +3 -3
  11. package/dist/cli/index.d.ts +3 -3
  12. package/dist/cli/index.js +1337 -67
  13. package/dist/cli/index.js.map +1 -1
  14. package/dist/{model-form-Cx3wtvi8.d.ts → client-B7EQ_hPV.d.cts} +606 -118
  15. package/dist/{model-form-_ugfOXao.d.cts → client-BYii6dU9.d.ts} +606 -118
  16. package/dist/index.cjs +1540 -113
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.cts +8 -7
  19. package/dist/index.d.ts +8 -7
  20. package/dist/index.js +1530 -114
  21. package/dist/index.js.map +1 -1
  22. package/dist/model-form-ByvyyvxB.d.ts +96 -0
  23. package/dist/model-form-DACdBLYG.d.cts +96 -0
  24. package/dist/{react-email-CiiSVa9F.d.cts → module-DC96HJa3.d.cts} +130 -5
  25. package/dist/{react-email-WN8UU3AL.d.ts → module-DbHlxpeR.d.ts} +130 -5
  26. package/dist/next/client.cjs +8591 -0
  27. package/dist/next/client.cjs.map +1 -0
  28. package/dist/next/client.d.cts +24 -0
  29. package/dist/next/client.d.ts +24 -0
  30. package/dist/next/client.js +8589 -0
  31. package/dist/next/client.js.map +1 -0
  32. package/dist/next/server.cjs +8709 -0
  33. package/dist/next/server.cjs.map +1 -0
  34. package/dist/next/server.d.cts +52 -0
  35. package/dist/next/server.d.ts +52 -0
  36. package/dist/next/server.js +8706 -0
  37. package/dist/next/server.js.map +1 -0
  38. package/dist/{pipeline-BtD-Uo5X.d.cts → pipeline-CmUZsXsi.d.cts} +1 -1
  39. package/dist/{pipeline-yCIZNJHE.d.ts → pipeline-DZMsPxUg.d.ts} +1 -1
  40. package/dist/react.cjs +30 -1
  41. package/dist/react.cjs.map +1 -1
  42. package/dist/react.d.cts +38 -10
  43. package/dist/react.d.ts +38 -10
  44. package/dist/react.js +30 -2
  45. package/dist/react.js.map +1 -1
  46. package/dist/shared-BMVGMnti.d.cts +35 -0
  47. package/dist/shared-DRptGBWP.d.ts +35 -0
  48. package/dist/{types-g8G6J0xE.d.cts → types-BeZIHduP.d.cts} +2 -1
  49. package/dist/{types-g8G6J0xE.d.ts → types-BeZIHduP.d.ts} +2 -1
  50. package/dist/{types-C2kiTt6-.d.ts → types-C-YvfgYh.d.cts} +26 -2
  51. package/dist/{types-89EfjLjV.d.cts → types-CRjDwmtJ.d.ts} +26 -2
  52. package/package.json +32 -14
package/dist/index.js CHANGED
@@ -664,8 +664,8 @@ function deleteSessionCookie(ctx, skipDontRememberMe) {
664
664
  expireCookie(ctx, ctx.context.authCookies.dontRememberToken);
665
665
  }
666
666
  }
667
- var getSessionCookie = (request, config) => {
668
- const cookies = (request instanceof Headers || !("headers" in request) ? request : request.headers).get("cookie");
667
+ var getSessionCookie = (request2, config) => {
668
+ const cookies = (request2 instanceof Headers || !("headers" in request2) ? request2 : request2.headers).get("cookie");
669
669
  if (!cookies) {
670
670
  return null;
671
671
  }
@@ -685,8 +685,8 @@ var getSessionCookie = (request, config) => {
685
685
  }
686
686
  return null;
687
687
  };
688
- var getCookieCache = async (request, config) => {
689
- const headers = request instanceof Headers || !("headers" in request) ? request : request.headers;
688
+ var getCookieCache = async (request2, config) => {
689
+ const headers = request2 instanceof Headers || !("headers" in request2) ? request2 : request2.headers;
690
690
  const cookieHeader = headers.get("cookie");
691
691
  if (!cookieHeader) {
692
692
  return null;
@@ -804,7 +804,7 @@ var getCookieCache = async (request, config) => {
804
804
 
805
805
  // package.json
806
806
  var package_default = {
807
- version: "2.8.2"
807
+ version: "2.10.0"
808
808
  };
809
809
 
810
810
  // src/sdk-version.ts
@@ -817,6 +817,7 @@ function buildSdkHeaderValue(sdkName) {
817
817
  var DEFAULT_CLIENT = "railway_direct";
818
818
  var SDK_NAME = "xylex-group/athena";
819
819
  var SDK_HEADER_VALUE = buildSdkHeaderValue(SDK_NAME);
820
+ var NO_CACHE_HEADER_VALUE = "no-cache";
820
821
  function parseResponseBody(rawText, contentType) {
821
822
  if (!rawText) {
822
823
  return { parsed: null, parseFailed: false };
@@ -835,6 +836,9 @@ function parseResponseBody(rawText, contentType) {
835
836
  function normalizeHeaderValue(value) {
836
837
  return value ? value : void 0;
837
838
  }
839
+ function isCacheControlHeaderName(name) {
840
+ return name.toLowerCase() === "cache-control";
841
+ }
838
842
  function resolveHeaderValue(headers, candidates) {
839
843
  for (const candidate of candidates) {
840
844
  const direct = normalizeHeaderValue(headers[candidate]);
@@ -993,6 +997,7 @@ function buildRpcGetEndpoint(payload) {
993
997
  }
994
998
  function buildHeaders(config, options) {
995
999
  const mergedStripNulls = options?.stripNulls ?? true;
1000
+ const forceNoCache = Boolean(config.forceNoCache || options?.forceNoCache);
996
1001
  const extraHeaders = {
997
1002
  ...config.headers ?? {},
998
1003
  ...options?.headers ?? {}
@@ -1046,11 +1051,15 @@ function buildHeaders(config, options) {
1046
1051
  const athenaClientKeys = ["x-athena-client", "X-Athena-Client"];
1047
1052
  Object.entries(extraHeaders).forEach(([key, value]) => {
1048
1053
  if (athenaClientKeys.includes(key)) return;
1054
+ if (forceNoCache && isCacheControlHeaderName(key)) return;
1049
1055
  const normalized = normalizeHeaderValue(value);
1050
1056
  if (normalized) {
1051
1057
  headers[key] = normalized;
1052
1058
  }
1053
1059
  });
1060
+ if (forceNoCache) {
1061
+ headers["Cache-Control"] = NO_CACHE_HEADER_VALUE;
1062
+ }
1054
1063
  return headers;
1055
1064
  }
1056
1065
  function toInvalidUrlResponse(error, endpoint, method) {
@@ -1511,6 +1520,45 @@ function identifier(...segments) {
1511
1520
  return new SqlIdentifierPath(expandedSegments);
1512
1521
  }
1513
1522
 
1523
+ // src/auth/limits.ts
1524
+ var ATHENA_AUTH_MAX_ADMIN_JSON_BYTES = 32 * 1024;
1525
+ var ATHENA_AUTH_MAX_ADMIN_JSON_DEPTH = 8;
1526
+ var ATHENA_AUTH_MAX_TEMPLATE_VARIABLES = 64;
1527
+ var ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH = 128;
1528
+ var ATHENA_AUTH_ADMIN_LIMITS = {
1529
+ maxAdminJsonBytes: ATHENA_AUTH_MAX_ADMIN_JSON_BYTES,
1530
+ maxAdminJsonDepth: ATHENA_AUTH_MAX_ADMIN_JSON_DEPTH,
1531
+ maxTemplateVariables: ATHENA_AUTH_MAX_TEMPLATE_VARIABLES,
1532
+ maxTemplateVariableLength: ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH
1533
+ };
1534
+ function describeTemplateVariableTarget(target) {
1535
+ const normalized = target?.trim();
1536
+ return normalized && normalized.length > 0 ? normalized : "Athena auth admin email template variables";
1537
+ }
1538
+ function assertAthenaAuthTemplateVariables(variables, target) {
1539
+ const label = describeTemplateVariableTarget(target);
1540
+ if (!Array.isArray(variables)) {
1541
+ throw new Error(`${label} must be an array of strings.`);
1542
+ }
1543
+ if (variables.length > ATHENA_AUTH_MAX_TEMPLATE_VARIABLES) {
1544
+ throw new Error(
1545
+ `${label} cannot contain more than ${ATHENA_AUTH_MAX_TEMPLATE_VARIABLES} entries.`
1546
+ );
1547
+ }
1548
+ variables.forEach((variable, index) => {
1549
+ if (typeof variable !== "string") {
1550
+ throw new Error(
1551
+ `${label} must contain only strings. Received ${typeof variable} at index ${index}.`
1552
+ );
1553
+ }
1554
+ if (variable.length > ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH) {
1555
+ throw new Error(
1556
+ `${label} cannot contain entries longer than ${ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH} characters. Received ${variable.length} characters at index ${index}.`
1557
+ );
1558
+ }
1559
+ });
1560
+ }
1561
+
1514
1562
  // src/auth/react-email.ts
1515
1563
  var reactEmailRenderModulePromise;
1516
1564
  function isRecord2(value) {
@@ -1740,6 +1788,7 @@ async function resolveReactEmailPayloadFields(input, fields, options) {
1740
1788
  var DEFAULT_AUTH_BASE_URL = "http://localhost:3001/api/auth";
1741
1789
  var SDK_NAME2 = "xylex-group/athena-auth";
1742
1790
  var SDK_HEADER_VALUE2 = buildSdkHeaderValue(SDK_NAME2);
1791
+ var NO_CACHE_HEADER_VALUE2 = "no-cache";
1743
1792
  function normalizeBaseUrl(baseUrl) {
1744
1793
  return (baseUrl ?? DEFAULT_AUTH_BASE_URL).replace(/\/$/, "");
1745
1794
  }
@@ -1749,6 +1798,9 @@ function isRecord3(value) {
1749
1798
  function normalizeHeaderValue2(value) {
1750
1799
  return value ? value : void 0;
1751
1800
  }
1801
+ function isCacheControlHeaderName2(name) {
1802
+ return name.toLowerCase() === "cache-control";
1803
+ }
1752
1804
  function parseResponseBody2(rawText, contentType) {
1753
1805
  if (!rawText) {
1754
1806
  return { parsed: null, parseFailed: false };
@@ -1804,6 +1856,98 @@ function mergeCallOptions(base, override) {
1804
1856
  }
1805
1857
  };
1806
1858
  }
1859
+ function copyDefinedField(target, source, targetKey, sourceKey) {
1860
+ if (!(sourceKey in source)) {
1861
+ return;
1862
+ }
1863
+ const value = source[sourceKey];
1864
+ if (value !== void 0) {
1865
+ target[targetKey] = value;
1866
+ }
1867
+ }
1868
+ function normalizeAdminEmailTemplatePayload(payload) {
1869
+ const normalized = { ...payload };
1870
+ copyDefinedField(normalized, payload, "template_key", "templateKey");
1871
+ copyDefinedField(normalized, payload, "event_type", "eventType");
1872
+ copyDefinedField(normalized, payload, "subject_template", "subjectTemplate");
1873
+ copyDefinedField(normalized, payload, "text_template", "textTemplate");
1874
+ copyDefinedField(normalized, payload, "html_template", "htmlTemplate");
1875
+ copyDefinedField(normalized, payload, "variable_bindings", "variableBindings");
1876
+ copyDefinedField(normalized, payload, "attachment_failure_mode", "attachmentFailureMode");
1877
+ copyDefinedField(normalized, payload, "is_active", "isActive");
1878
+ return normalized;
1879
+ }
1880
+ function toReactEmailTemplateCompatibilityInput(input) {
1881
+ const payload = input;
1882
+ const compatibility = { ...payload };
1883
+ copyDefinedField(compatibility, payload, "templateKey", "template_key");
1884
+ copyDefinedField(compatibility, payload, "eventType", "event_type");
1885
+ copyDefinedField(compatibility, payload, "subjectTemplate", "subject_template");
1886
+ copyDefinedField(compatibility, payload, "textTemplate", "text_template");
1887
+ copyDefinedField(compatibility, payload, "htmlTemplate", "html_template");
1888
+ copyDefinedField(compatibility, payload, "variableBindings", "variable_bindings");
1889
+ copyDefinedField(compatibility, payload, "attachmentFailureMode", "attachment_failure_mode");
1890
+ copyDefinedField(compatibility, payload, "isActive", "is_active");
1891
+ return compatibility;
1892
+ }
1893
+ function normalizeAdminEmailTemplateSendPayload(payload) {
1894
+ const normalized = { ...payload };
1895
+ copyDefinedField(normalized, payload, "template_id", "templateId");
1896
+ copyDefinedField(normalized, payload, "recipient_email", "recipientEmail");
1897
+ copyDefinedField(normalized, payload, "render_variables", "renderVariables");
1898
+ copyDefinedField(normalized, payload, "user_id", "userId");
1899
+ copyDefinedField(normalized, payload, "organization_id", "organizationId");
1900
+ copyDefinedField(normalized, payload, "session_token", "sessionToken");
1901
+ return normalized;
1902
+ }
1903
+ function toSessionGuardFailure(sessionResult) {
1904
+ if (sessionResult.status === 401 || sessionResult.data == null) {
1905
+ return {
1906
+ ok: false,
1907
+ reason: "unauthorized",
1908
+ status: 401,
1909
+ error: sessionResult.error ?? "Unauthorized",
1910
+ sessionResult
1911
+ };
1912
+ }
1913
+ return {
1914
+ ok: false,
1915
+ reason: "upstream_error",
1916
+ status: sessionResult.status,
1917
+ error: sessionResult.error ?? "Failed to resolve current session",
1918
+ sessionResult
1919
+ };
1920
+ }
1921
+ function toPermissionGuardFailure(permissionResult, sessionResult) {
1922
+ if (permissionResult.status === 401) {
1923
+ return {
1924
+ ok: false,
1925
+ reason: "unauthorized",
1926
+ status: 401,
1927
+ error: permissionResult.error ?? "Unauthorized",
1928
+ sessionResult,
1929
+ permissionResult
1930
+ };
1931
+ }
1932
+ if (permissionResult.status === 403) {
1933
+ return {
1934
+ ok: false,
1935
+ reason: "forbidden",
1936
+ status: 403,
1937
+ error: permissionResult.error ?? "Forbidden",
1938
+ sessionResult,
1939
+ permissionResult
1940
+ };
1941
+ }
1942
+ return {
1943
+ ok: false,
1944
+ reason: "upstream_error",
1945
+ status: permissionResult.status,
1946
+ error: permissionResult.error ?? "Failed to resolve permission check",
1947
+ sessionResult,
1948
+ permissionResult
1949
+ };
1950
+ }
1807
1951
  function extractFetchOptions(input) {
1808
1952
  if (!input) {
1809
1953
  return {
@@ -1819,6 +1963,7 @@ function extractFetchOptions(input) {
1819
1963
  };
1820
1964
  }
1821
1965
  function buildHeaders2(config, options) {
1966
+ const forceNoCache = Boolean(config.forceNoCache || options?.forceNoCache);
1822
1967
  const headers = {
1823
1968
  "Content-Type": "application/json",
1824
1969
  "X-Athena-Sdk": SDK_HEADER_VALUE2
@@ -1832,16 +1977,30 @@ function buildHeaders2(config, options) {
1832
1977
  if (bearerToken) {
1833
1978
  headers.Authorization = `Bearer ${bearerToken}`;
1834
1979
  }
1980
+ const cookie = options?.cookie ?? config.cookie;
1981
+ if (cookie) {
1982
+ headers.Cookie = cookie;
1983
+ }
1984
+ const sessionToken = options?.sessionToken ?? config.sessionToken;
1985
+ if (sessionToken) {
1986
+ headers["X-Athena-Auth-Session-Token"] = sessionToken;
1987
+ }
1835
1988
  const mergedExtraHeaders = {
1836
1989
  ...config.headers ?? {},
1837
1990
  ...options?.headers ?? {}
1838
1991
  };
1839
1992
  Object.entries(mergedExtraHeaders).forEach(([key, value]) => {
1993
+ if (forceNoCache && isCacheControlHeaderName2(key)) {
1994
+ return;
1995
+ }
1840
1996
  const normalized = normalizeHeaderValue2(value);
1841
1997
  if (normalized) {
1842
1998
  headers[key] = normalized;
1843
1999
  }
1844
2000
  });
2001
+ if (forceNoCache) {
2002
+ headers["Cache-Control"] = NO_CACHE_HEADER_VALUE2;
2003
+ }
1845
2004
  return headers;
1846
2005
  }
1847
2006
  function appendQueryParam(searchParams, key, value) {
@@ -2047,7 +2206,7 @@ function createAuthClient(config = {}) {
2047
2206
  ...config,
2048
2207
  baseUrl: normalizedBaseUrl
2049
2208
  };
2050
- const request = (input, options) => {
2209
+ const request2 = (input, options) => {
2051
2210
  const method = input.method ?? (input.body !== void 0 ? "POST" : inferDefaultMethod(input.endpoint));
2052
2211
  const mergedOptions = mergeCallOptions(input.fetchOptions, options);
2053
2212
  return callAuthEndpoint(
@@ -2060,7 +2219,7 @@ function createAuthClient(config = {}) {
2060
2219
  };
2061
2220
  const postGeneric = (endpoint, input, options) => {
2062
2221
  const { payload, fetchOptions } = extractFetchOptions(input);
2063
- return request(
2222
+ return request2(
2064
2223
  {
2065
2224
  endpoint,
2066
2225
  method: "POST",
@@ -2072,7 +2231,7 @@ function createAuthClient(config = {}) {
2072
2231
  };
2073
2232
  const getGeneric = (endpoint, input, options) => {
2074
2233
  const { fetchOptions } = extractFetchOptions(input);
2075
- return request(
2234
+ return request2(
2076
2235
  {
2077
2236
  endpoint,
2078
2237
  method: "GET",
@@ -2084,7 +2243,7 @@ function createAuthClient(config = {}) {
2084
2243
  const getWithQuery = (endpoint, input, options) => {
2085
2244
  const { payload, fetchOptions } = extractFetchOptions(input);
2086
2245
  const query = payload?.query;
2087
- return request(
2246
+ return request2(
2088
2247
  {
2089
2248
  endpoint,
2090
2249
  method: "GET",
@@ -2102,11 +2261,96 @@ function createAuthClient(config = {}) {
2102
2261
  htmlField: "htmlBody",
2103
2262
  textField: "textBody"
2104
2263
  }, withReactEmailRoute(route));
2105
- const resolveAdminEmailTemplatePayload = (route, input) => resolveReactEmailPayloadFields(input, {
2264
+ const resolveAdminEmailTemplatePayload = (route, input) => resolveReactEmailPayloadFields(toReactEmailTemplateCompatibilityInput(input), {
2106
2265
  htmlField: "htmlTemplate",
2107
2266
  textField: "textTemplate",
2108
2267
  variablesField: "variables"
2109
- }, withReactEmailRoute(route));
2268
+ }, withReactEmailRoute(route)).then((payload) => {
2269
+ const normalizedPayload = normalizeAdminEmailTemplatePayload(payload);
2270
+ if ("variables" in payload && payload.variables !== void 0 && payload.variables !== null) {
2271
+ assertAthenaAuthTemplateVariables(
2272
+ payload.variables,
2273
+ `${route} variables`
2274
+ );
2275
+ }
2276
+ return normalizedPayload;
2277
+ });
2278
+ const requireSession = async (input, options) => {
2279
+ const sessionInput = input?.fetchOptions ? { fetchOptions: input.fetchOptions } : void 0;
2280
+ const sessionResult = await getGeneric(
2281
+ "/get-session",
2282
+ sessionInput,
2283
+ options
2284
+ );
2285
+ if (!sessionResult.ok || sessionResult.data == null) {
2286
+ return toSessionGuardFailure(sessionResult);
2287
+ }
2288
+ return {
2289
+ ok: true,
2290
+ session: sessionResult.data
2291
+ };
2292
+ };
2293
+ const getUser = async (input, options) => {
2294
+ const sessionResult = await getGeneric(
2295
+ "/get-session",
2296
+ input,
2297
+ options
2298
+ );
2299
+ if (!sessionResult.ok) {
2300
+ return {
2301
+ ...sessionResult,
2302
+ data: null
2303
+ };
2304
+ }
2305
+ return {
2306
+ ...sessionResult,
2307
+ data: {
2308
+ user: sessionResult.data?.user ?? null
2309
+ }
2310
+ };
2311
+ };
2312
+ const requirePermission = async (endpoint, input, options) => {
2313
+ const sessionGuard = await requireSession(
2314
+ input?.fetchOptions ? { fetchOptions: input.fetchOptions } : void 0,
2315
+ options
2316
+ );
2317
+ if (!sessionGuard.ok) {
2318
+ return sessionGuard;
2319
+ }
2320
+ const permissionResult = await postGeneric(
2321
+ endpoint,
2322
+ input,
2323
+ options
2324
+ );
2325
+ if (!permissionResult.ok) {
2326
+ return toPermissionGuardFailure(permissionResult, {
2327
+ ok: true,
2328
+ status: 200,
2329
+ data: sessionGuard.session,
2330
+ error: null,
2331
+ errorDetails: null,
2332
+ raw: sessionGuard.session
2333
+ });
2334
+ }
2335
+ if (!permissionResult.data?.success) {
2336
+ return {
2337
+ ok: false,
2338
+ reason: "forbidden",
2339
+ status: 403,
2340
+ error: permissionResult.data?.error ?? "Forbidden",
2341
+ sessionResult: {
2342
+ ok: true,
2343
+ status: 200,
2344
+ data: sessionGuard.session,
2345
+ error: null,
2346
+ errorDetails: null,
2347
+ raw: sessionGuard.session
2348
+ },
2349
+ permissionResult
2350
+ };
2351
+ }
2352
+ return sessionGuard;
2353
+ };
2110
2354
  const listUserEmailsWithFallback = async (input, options) => {
2111
2355
  const primary = await getWithQuery(
2112
2356
  "/email/list",
@@ -2268,6 +2512,7 @@ function createAuthClient(config = {}) {
2268
2512
  input,
2269
2513
  options
2270
2514
  ),
2515
+ requirePermission: (input, options) => requirePermission("/organization/has-permission", input, options),
2271
2516
  invitation: {
2272
2517
  cancel: (input, options) => executePostWithCompatibleInput(
2273
2518
  resolvedConfig,
@@ -2463,6 +2708,8 @@ function createAuthClient(config = {}) {
2463
2708
  };
2464
2709
  const auth = {
2465
2710
  getSession: (input, options) => getGeneric("/get-session", input, options),
2711
+ getUser,
2712
+ requireSession,
2466
2713
  signOut,
2467
2714
  forgetPassword: (input, options) => postGeneric("/forget-password", input, options),
2468
2715
  resetPassword: authResetPassword,
@@ -2557,6 +2804,7 @@ function createAuthClient(config = {}) {
2557
2804
  }
2558
2805
  },
2559
2806
  hasPermission: (input, options) => postGeneric("/admin/has-permission", input, options),
2807
+ requirePermission: (input, options) => requirePermission("/admin/has-permission", input, options),
2560
2808
  apiKey: {
2561
2809
  create: (input, options) => postGeneric("/admin/api-key/create", input, options)
2562
2810
  },
@@ -2601,7 +2849,15 @@ function createAuthClient(config = {}) {
2601
2849
  await resolveAdminEmailTemplatePayload("/admin/email-template/update", input),
2602
2850
  options
2603
2851
  ),
2604
- delete: (input, options) => postGeneric("/admin/email-template/delete", input, options)
2852
+ delete: (input, options) => postGeneric("/admin/email-template/delete", input, options),
2853
+ send: (input, options) => postGeneric(
2854
+ "/admin/email-template/send",
2855
+ normalizeAdminEmailTemplateSendPayload(extractFetchOptions(input).payload),
2856
+ options
2857
+ )
2858
+ },
2859
+ eventType: {
2860
+ list: (input, options) => getWithQuery("/admin/email-event-type/list", input, options)
2605
2861
  }
2606
2862
  },
2607
2863
  emailTemplate: {
@@ -2617,7 +2873,15 @@ function createAuthClient(config = {}) {
2617
2873
  "/admin/email-template/update",
2618
2874
  await resolveAdminEmailTemplatePayload("/admin/email-template/update", input),
2619
2875
  options
2876
+ ),
2877
+ send: (input, options) => postGeneric(
2878
+ "/admin/email-template/send",
2879
+ normalizeAdminEmailTemplateSendPayload(extractFetchOptions(input).payload),
2880
+ options
2620
2881
  )
2882
+ },
2883
+ emailEventType: {
2884
+ list: (input, options) => getWithQuery("/admin/email-event-type/list", input, options)
2621
2885
  }
2622
2886
  },
2623
2887
  apiKey: {
@@ -2657,7 +2921,7 @@ function createAuthClient(config = {}) {
2657
2921
  throw new Error("callback.provider requires non-empty code and state values");
2658
2922
  }
2659
2923
  const endpoint = `/callback/${encodeURIComponent(provider)}`;
2660
- return request({
2924
+ return request2({
2661
2925
  endpoint,
2662
2926
  method: "GET",
2663
2927
  query: {
@@ -2671,7 +2935,7 @@ function createAuthClient(config = {}) {
2671
2935
  };
2672
2936
  return {
2673
2937
  baseUrl: normalizedBaseUrl,
2674
- request,
2938
+ request: request2,
2675
2939
  signIn: {
2676
2940
  email: (input, options) => executePostWithCompatibleInput(
2677
2941
  resolvedConfig,
@@ -2708,6 +2972,8 @@ function createAuthClient(config = {}) {
2708
2972
  input,
2709
2973
  options
2710
2974
  ),
2975
+ getUser,
2976
+ requireSession,
2711
2977
  listSessions: (input, options) => executeGetWithCompatibleInput(
2712
2978
  resolvedConfig,
2713
2979
  { endpoint: "/list-sessions", method: "GET" },
@@ -3410,16 +3676,16 @@ function createStorageFileModule(base, config = {}) {
3410
3676
  };
3411
3677
  });
3412
3678
  input.onProgress?.(createProgressSnapshot("preparing", sources, 0, 0, 0));
3413
- const uploadUrls = uploadRequests.length === 1 ? [await base.createStorageUploadUrl(uploadRequests[0].uploadRequest, options)] : (await base.createStorageUploadUrls({ files: uploadRequests.map((request) => request.uploadRequest) }, options)).files;
3679
+ const uploadUrls = uploadRequests.length === 1 ? [await base.createStorageUploadUrl(uploadRequests[0].uploadRequest, options)] : (await base.createStorageUploadUrls({ files: uploadRequests.map((request2) => request2.uploadRequest) }, options)).files;
3414
3680
  const aggregateLoaded = new Array(uploadRequests.length).fill(0);
3415
3681
  const uploaded = [];
3416
3682
  for (let index = 0; index < uploadRequests.length; index += 1) {
3417
- const request = uploadRequests[index];
3683
+ const request2 = uploadRequests[index];
3418
3684
  const uploadUrl = uploadUrls[index];
3419
3685
  const response = await putUploadBody(
3420
3686
  uploadUrl.upload.url,
3421
3687
  uploadUrl.upload.headers ?? {},
3422
- request.source,
3688
+ request2.source,
3423
3689
  input,
3424
3690
  options,
3425
3691
  (progress) => {
@@ -3430,13 +3696,13 @@ function createStorageFileModule(base, config = {}) {
3430
3696
  uploaded.push({
3431
3697
  file: uploadUrl.file,
3432
3698
  upload: uploadUrl.upload,
3433
- source: request.source.source,
3434
- fileName: request.source.fileName,
3435
- storage_key: request.uploadRequest.storage_key,
3699
+ source: request2.source.source,
3700
+ fileName: request2.source.fileName,
3701
+ storage_key: request2.uploadRequest.storage_key,
3436
3702
  response
3437
3703
  });
3438
- aggregateLoaded[index] = request.source.sizeBytes;
3439
- input.onProgress?.(createProgressSnapshot("complete", sources, index, request.source.sizeBytes, sum(aggregateLoaded)));
3704
+ aggregateLoaded[index] = request2.source.sizeBytes;
3705
+ input.onProgress?.(createProgressSnapshot("complete", sources, index, request2.source.sizeBytes, sum(aggregateLoaded)));
3440
3706
  }
3441
3707
  return {
3442
3708
  files: uploaded,
@@ -5411,6 +5677,517 @@ function createStorageModule(gateway, runtimeOptions) {
5411
5677
  };
5412
5678
  }
5413
5679
 
5680
+ // src/chat/module.ts
5681
+ var SDK_NAME3 = "xylex-group/athena-chat";
5682
+ var SDK_HEADER_VALUE3 = buildSdkHeaderValue(SDK_NAME3);
5683
+ var NO_CACHE_HEADER_VALUE3 = "no-cache";
5684
+ var AthenaChatError = class extends Error {
5685
+ status;
5686
+ endpoint;
5687
+ method;
5688
+ requestId;
5689
+ body;
5690
+ constructor(input) {
5691
+ super(input.message);
5692
+ this.name = "AthenaChatError";
5693
+ this.status = input.status;
5694
+ this.endpoint = input.endpoint;
5695
+ this.method = input.method;
5696
+ this.requestId = input.requestId;
5697
+ this.body = input.body;
5698
+ }
5699
+ };
5700
+ function deriveRealtimeInfoUrl(wsUrl) {
5701
+ if (!wsUrl) {
5702
+ return void 0;
5703
+ }
5704
+ const parsed = new URL(normalizeWsUrl(wsUrl, "Athena chat WebSocket URL"));
5705
+ parsed.protocol = parsed.protocol === "wss:" ? "https:" : "http:";
5706
+ parsed.pathname = parsed.pathname.replace(/\/wss\/gateway$/, "/wss/info");
5707
+ return parsed.toString();
5708
+ }
5709
+ function normalizeWsUrl(value, label) {
5710
+ const normalized = value.trim();
5711
+ if (!normalized) {
5712
+ throw new Error(`${label} is required.`);
5713
+ }
5714
+ let parsed;
5715
+ try {
5716
+ parsed = new URL(normalized);
5717
+ } catch {
5718
+ throw new Error(`${label} must be a valid absolute ws(s) URL.`);
5719
+ }
5720
+ if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") {
5721
+ throw new Error(`${label} must use ws or wss.`);
5722
+ }
5723
+ parsed.pathname = parsed.pathname.replace(/\/+$/, "");
5724
+ return parsed.toString().replace(/\/$/, "");
5725
+ }
5726
+ function isRecord7(value) {
5727
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
5728
+ }
5729
+ function normalizeHeaderValue3(value) {
5730
+ return value ? value : void 0;
5731
+ }
5732
+ function parseResponseBody4(rawText, contentType) {
5733
+ if (!rawText) {
5734
+ return { parsed: null, parseFailed: false };
5735
+ }
5736
+ const contentTypeSuggestsJson = contentType?.toLowerCase().includes("application/json") ?? false;
5737
+ const looksJson = contentTypeSuggestsJson || rawText.startsWith("{") || rawText.startsWith("[");
5738
+ if (!looksJson) {
5739
+ return { parsed: rawText, parseFailed: false };
5740
+ }
5741
+ try {
5742
+ return { parsed: JSON.parse(rawText), parseFailed: false };
5743
+ } catch {
5744
+ return { parsed: rawText, parseFailed: true };
5745
+ }
5746
+ }
5747
+ function resolveRequestId3(headers) {
5748
+ return headers.get("x-request-id") ?? headers.get("x-correlation-id") ?? headers.get("x-athena-request-id") ?? void 0;
5749
+ }
5750
+ function resolveErrorMessage4(payload, fallback) {
5751
+ if (isRecord7(payload)) {
5752
+ for (const candidate of [payload.error, payload.message, payload.details]) {
5753
+ if (typeof candidate === "string" && candidate.trim().length > 0) {
5754
+ return candidate.trim();
5755
+ }
5756
+ }
5757
+ }
5758
+ if (typeof payload === "string" && payload.trim().length > 0) {
5759
+ return payload.trim();
5760
+ }
5761
+ return fallback;
5762
+ }
5763
+ function encodePathSegment(value, label) {
5764
+ const normalized = value.trim();
5765
+ if (!normalized) {
5766
+ throw new Error(`${label} is required.`);
5767
+ }
5768
+ return encodeURIComponent(normalized);
5769
+ }
5770
+ function encodeQuery(query) {
5771
+ if (!query) {
5772
+ return "";
5773
+ }
5774
+ const params = new URLSearchParams();
5775
+ for (const [key, value] of Object.entries(query)) {
5776
+ if (value === void 0 || value === null) {
5777
+ continue;
5778
+ }
5779
+ if (Array.isArray(value)) {
5780
+ for (const item of value) {
5781
+ if (item !== void 0 && item !== null) {
5782
+ params.append(key, String(item));
5783
+ }
5784
+ }
5785
+ continue;
5786
+ }
5787
+ params.set(key, String(value));
5788
+ }
5789
+ const encoded = params.toString();
5790
+ return encoded ? `?${encoded}` : "";
5791
+ }
5792
+ function createSocket(factory, url, protocols) {
5793
+ try {
5794
+ return new factory(url, protocols);
5795
+ } catch (error) {
5796
+ if (error instanceof TypeError) {
5797
+ return factory(url, protocols);
5798
+ }
5799
+ throw error;
5800
+ }
5801
+ }
5802
+ function buildHeaders3(config, options) {
5803
+ const headers = {
5804
+ Accept: "application/json",
5805
+ apikey: config.apiKey,
5806
+ "x-api-key": config.apiKey,
5807
+ "X-Athena-Sdk": SDK_HEADER_VALUE3
5808
+ };
5809
+ if (config.client || options?.client) {
5810
+ headers["X-Athena-Client"] = options?.client ?? config.client ?? "";
5811
+ }
5812
+ const bearerToken = options?.bearerToken ?? config.bearerToken;
5813
+ if (typeof bearerToken === "string" && bearerToken.trim()) {
5814
+ headers.Authorization = bearerToken.startsWith("Bearer ") ? bearerToken : `Bearer ${bearerToken}`;
5815
+ }
5816
+ const cookie = options?.cookie ?? config.cookie;
5817
+ if (typeof cookie === "string" && cookie.trim()) {
5818
+ headers.Cookie = cookie;
5819
+ }
5820
+ const sessionToken = options?.sessionToken ?? config.sessionToken;
5821
+ if (typeof sessionToken === "string" && sessionToken.trim()) {
5822
+ headers["X-Athena-Auth-Session-Token"] = sessionToken;
5823
+ }
5824
+ if (config.forceNoCache || options?.forceNoCache) {
5825
+ headers["Cache-Control"] = NO_CACHE_HEADER_VALUE3;
5826
+ }
5827
+ for (const source of [config.headers, options?.headers]) {
5828
+ for (const [key, value] of Object.entries(source ?? {})) {
5829
+ const normalized = normalizeHeaderValue3(value);
5830
+ if (normalized) {
5831
+ headers[key] = normalized;
5832
+ }
5833
+ }
5834
+ }
5835
+ return headers;
5836
+ }
5837
+ function withJsonBody(init, body) {
5838
+ return {
5839
+ ...init,
5840
+ body: body === void 0 ? void 0 : JSON.stringify(body),
5841
+ headers: {
5842
+ "Content-Type": "application/json",
5843
+ ...init.headers
5844
+ }
5845
+ };
5846
+ }
5847
+ async function request(config, method, endpoint, options, body) {
5848
+ if (!config.baseUrl) {
5849
+ throw new Error(
5850
+ "Athena chat base URL is not configured. Pass createClient({ url }) for unified routing or set chat.url / chatUrl explicitly."
5851
+ );
5852
+ }
5853
+ const url = `${config.baseUrl}${endpoint}`;
5854
+ const init = {
5855
+ method,
5856
+ headers: buildHeaders3(config, options),
5857
+ signal: options?.signal
5858
+ };
5859
+ const finalInit = body === void 0 || method === "GET" ? init : withJsonBody(init, body);
5860
+ const response = await fetch(url, finalInit);
5861
+ const rawText = await response.text();
5862
+ const { parsed } = parseResponseBody4(rawText, response.headers.get("content-type"));
5863
+ if (!response.ok) {
5864
+ throw new AthenaChatError({
5865
+ message: resolveErrorMessage4(parsed, `Athena chat ${method} ${endpoint} failed with ${response.status}`),
5866
+ status: response.status,
5867
+ endpoint,
5868
+ method,
5869
+ requestId: resolveRequestId3(response.headers),
5870
+ body: parsed
5871
+ });
5872
+ }
5873
+ return parsed;
5874
+ }
5875
+ function unwrapEnvelopeData(payload) {
5876
+ return payload.data;
5877
+ }
5878
+ function createRealtimeConnection(config, options) {
5879
+ if (!config.wsUrl) {
5880
+ throw new Error(
5881
+ "Athena chat WebSocket URL is not configured. Pass createClient({ url }) for unified routing or set chat.wsUrl / chatWsUrl explicitly."
5882
+ );
5883
+ }
5884
+ const wsFactory = config.webSocketFactory ?? globalThis.WebSocket;
5885
+ if (!wsFactory) {
5886
+ throw new Error(
5887
+ "No WebSocket implementation is available. Provide chat.webSocketFactory in createClient(...) or run in a runtime with global WebSocket support."
5888
+ );
5889
+ }
5890
+ const socket = createSocket(wsFactory, config.wsUrl, options?.protocols);
5891
+ const send = (command) => {
5892
+ socket.send(JSON.stringify(command));
5893
+ };
5894
+ if (options?.onMessage) {
5895
+ const listener = (event) => {
5896
+ const messageEvent = event;
5897
+ const raw = messageEvent?.data;
5898
+ if (typeof raw !== "string") {
5899
+ return;
5900
+ }
5901
+ try {
5902
+ options.onMessage?.(JSON.parse(raw));
5903
+ } catch {
5904
+ options.onMessage?.({ type: "error", error: "Invalid JSON message from Athena chat realtime gateway." });
5905
+ }
5906
+ };
5907
+ if (typeof socket.addEventListener === "function") {
5908
+ socket.addEventListener("message", listener);
5909
+ } else {
5910
+ socket.onmessage = listener;
5911
+ }
5912
+ }
5913
+ const hello = (command) => {
5914
+ send({
5915
+ type: "auth.hello",
5916
+ token: command?.token,
5917
+ room_subscriptions: command?.room_subscriptions
5918
+ });
5919
+ };
5920
+ if (options?.hello) {
5921
+ const onOpen = () => hello({
5922
+ token: options.hello?.token ?? void 0,
5923
+ room_subscriptions: options.hello?.room_subscriptions ?? void 0
5924
+ });
5925
+ if (typeof socket.addEventListener === "function") {
5926
+ socket.addEventListener("open", onOpen);
5927
+ } else {
5928
+ socket.onopen = onOpen;
5929
+ }
5930
+ }
5931
+ return {
5932
+ socket,
5933
+ send,
5934
+ hello,
5935
+ subscribe(roomId, fromSeq) {
5936
+ send({
5937
+ type: "chat.subscribe",
5938
+ room_id: roomId,
5939
+ from_seq: fromSeq ?? void 0
5940
+ });
5941
+ },
5942
+ unsubscribe(roomId) {
5943
+ send({
5944
+ type: "chat.unsubscribe",
5945
+ room_id: roomId
5946
+ });
5947
+ },
5948
+ resume(rooms) {
5949
+ send({
5950
+ type: "chat.resume",
5951
+ rooms
5952
+ });
5953
+ },
5954
+ typingStart(roomId) {
5955
+ send({
5956
+ type: "chat.typing.start",
5957
+ room_id: roomId
5958
+ });
5959
+ },
5960
+ typingStop(roomId) {
5961
+ send({
5962
+ type: "chat.typing.stop",
5963
+ room_id: roomId
5964
+ });
5965
+ },
5966
+ presenceHeartbeat(activeRoomId) {
5967
+ send({
5968
+ type: "chat.presence.heartbeat",
5969
+ active_room_id: activeRoomId ?? void 0
5970
+ });
5971
+ },
5972
+ readUpTo(roomId, input) {
5973
+ send({
5974
+ type: "chat.read.up_to",
5975
+ room_id: roomId,
5976
+ message_id: input?.message_id ?? void 0,
5977
+ seq: input?.seq ?? void 0
5978
+ });
5979
+ },
5980
+ ping(at = (/* @__PURE__ */ new Date()).toISOString()) {
5981
+ send({
5982
+ type: "ping",
5983
+ at
5984
+ });
5985
+ },
5986
+ close(code, reason) {
5987
+ socket.close(code, reason);
5988
+ }
5989
+ };
5990
+ }
5991
+ function createChatModule(config) {
5992
+ const realtime = {
5993
+ info(options) {
5994
+ const realtimeInfoUrl = config.realtimeInfoUrl ?? deriveRealtimeInfoUrl(config.wsUrl);
5995
+ if (!realtimeInfoUrl) {
5996
+ throw new Error(
5997
+ "Athena chat realtime info URL is not configured. Pass createClient({ url }) for unified routing or set chat.wsUrl / chatWsUrl explicitly."
5998
+ );
5999
+ }
6000
+ return request(
6001
+ {
6002
+ ...config,
6003
+ baseUrl: realtimeInfoUrl
6004
+ },
6005
+ "GET",
6006
+ "",
6007
+ options
6008
+ );
6009
+ },
6010
+ connect(options) {
6011
+ return createRealtimeConnection(config, options);
6012
+ }
6013
+ };
6014
+ return {
6015
+ room: {
6016
+ list(query, options) {
6017
+ return request(
6018
+ config,
6019
+ "GET",
6020
+ `/rooms${encodeQuery(query)}`,
6021
+ options
6022
+ );
6023
+ },
6024
+ create(input, options) {
6025
+ return request(config, "POST", "/rooms", options, input);
6026
+ },
6027
+ get(roomId, options) {
6028
+ return request(
6029
+ config,
6030
+ "GET",
6031
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}`,
6032
+ options
6033
+ );
6034
+ },
6035
+ update(roomId, input, options) {
6036
+ return request(
6037
+ config,
6038
+ "PATCH",
6039
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}`,
6040
+ options,
6041
+ input
6042
+ );
6043
+ },
6044
+ archive(roomId, options) {
6045
+ return request(
6046
+ config,
6047
+ "POST",
6048
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/archive`,
6049
+ options
6050
+ );
6051
+ },
6052
+ readCursor: {
6053
+ upTo(roomId, input, options) {
6054
+ return request(
6055
+ config,
6056
+ "POST",
6057
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/read-cursor`,
6058
+ options,
6059
+ input ?? {}
6060
+ );
6061
+ }
6062
+ },
6063
+ member: {
6064
+ list(roomId, options) {
6065
+ return request(
6066
+ config,
6067
+ "GET",
6068
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/members`,
6069
+ options
6070
+ );
6071
+ },
6072
+ add(roomId, input, options) {
6073
+ return request(
6074
+ config,
6075
+ "POST",
6076
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/members`,
6077
+ options,
6078
+ input
6079
+ );
6080
+ },
6081
+ remove(roomId, userId, options) {
6082
+ return request(
6083
+ config,
6084
+ "DELETE",
6085
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/members/${encodePathSegment(userId, "chat user ID")}`,
6086
+ options
6087
+ );
6088
+ }
6089
+ },
6090
+ message: {
6091
+ list(roomId, query, options) {
6092
+ return request(
6093
+ config,
6094
+ "GET",
6095
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages${encodeQuery(query)}`,
6096
+ options
6097
+ );
6098
+ },
6099
+ send(roomId, input, options) {
6100
+ return request(
6101
+ config,
6102
+ "POST",
6103
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages`,
6104
+ options,
6105
+ input
6106
+ );
6107
+ },
6108
+ update(roomId, messageId, input, options) {
6109
+ return request(
6110
+ config,
6111
+ "PATCH",
6112
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages/${encodePathSegment(messageId, "chat message ID")}`,
6113
+ options,
6114
+ input
6115
+ );
6116
+ },
6117
+ delete(roomId, messageId, options) {
6118
+ return request(
6119
+ config,
6120
+ "DELETE",
6121
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages/${encodePathSegment(messageId, "chat message ID")}`,
6122
+ options
6123
+ );
6124
+ }
6125
+ }
6126
+ },
6127
+ message: {
6128
+ reaction: {
6129
+ add(messageId, input, options) {
6130
+ return request(
6131
+ config,
6132
+ "POST",
6133
+ `/messages/${encodePathSegment(messageId, "chat message ID")}/reactions`,
6134
+ options,
6135
+ input
6136
+ );
6137
+ },
6138
+ remove(messageId, emoji, options) {
6139
+ return request(
6140
+ config,
6141
+ "DELETE",
6142
+ `/messages/${encodePathSegment(messageId, "chat message ID")}/reactions/${encodePathSegment(emoji, "reaction emoji")}`,
6143
+ options
6144
+ );
6145
+ }
6146
+ },
6147
+ search(input, options) {
6148
+ return request(
6149
+ config,
6150
+ "POST",
6151
+ "/messages/search",
6152
+ options,
6153
+ input
6154
+ );
6155
+ }
6156
+ },
6157
+ realtime
6158
+ };
6159
+ }
6160
+ var chatSdkManifest = {
6161
+ namespace: "chat",
6162
+ basePath: "/chat",
6163
+ methods: [
6164
+ { name: "listRooms", method: "GET", path: "/chat/rooms" },
6165
+ { name: "createRoom", method: "POST", path: "/chat/rooms" },
6166
+ { name: "getRoom", method: "GET", path: "/chat/rooms/{room_id}" },
6167
+ { name: "updateRoom", method: "PATCH", path: "/chat/rooms/{room_id}" },
6168
+ { name: "archiveRoom", method: "POST", path: "/chat/rooms/{room_id}/archive" },
6169
+ { name: "listRoomMessages", method: "GET", path: "/chat/rooms/{room_id}/messages" },
6170
+ { name: "sendRoomMessage", method: "POST", path: "/chat/rooms/{room_id}/messages" },
6171
+ { name: "updateRoomMessage", method: "PATCH", path: "/chat/rooms/{room_id}/messages/{message_id}" },
6172
+ { name: "deleteRoomMessage", method: "DELETE", path: "/chat/rooms/{room_id}/messages/{message_id}" },
6173
+ { name: "advanceReadCursor", method: "POST", path: "/chat/rooms/{room_id}/read-cursor" },
6174
+ { name: "listRoomMembers", method: "GET", path: "/chat/rooms/{room_id}/members" },
6175
+ { name: "addRoomMembers", method: "POST", path: "/chat/rooms/{room_id}/members" },
6176
+ { name: "removeRoomMember", method: "DELETE", path: "/chat/rooms/{room_id}/members/{user_id}" },
6177
+ { name: "addReaction", method: "POST", path: "/chat/messages/{message_id}/reactions" },
6178
+ { name: "removeReaction", method: "DELETE", path: "/chat/messages/{message_id}/reactions/{emoji}" },
6179
+ { name: "searchMessages", method: "POST", path: "/chat/messages/search" },
6180
+ { name: "getRealtimeInfo", method: "GET", path: "/wss/info" },
6181
+ { name: "connectRealtime", method: "GET", path: "/wss/gateway" }
6182
+ ]
6183
+ };
6184
+ function unwrapChatRoom(payload) {
6185
+ return unwrapEnvelopeData(payload);
6186
+ }
6187
+ function unwrapChatMessage(payload) {
6188
+ return unwrapEnvelopeData(payload);
6189
+ }
6190
+
5414
6191
  // src/client-builder.ts
5415
6192
  var DEFAULT_BACKEND = { type: "athena" };
5416
6193
  function toBackendConfig(value) {
@@ -5463,6 +6240,9 @@ var AthenaClientBuilderImpl = class {
5463
6240
  apiKey;
5464
6241
  backendConfig = DEFAULT_BACKEND;
5465
6242
  clientName;
6243
+ defaultUserId;
6244
+ defaultOrganizationId;
6245
+ forceNoCacheEnabled = false;
5466
6246
  defaultHeaders;
5467
6247
  authConfig;
5468
6248
  dbUrlOverride;
@@ -5511,6 +6291,15 @@ var AthenaClientBuilderImpl = class {
5511
6291
  if (options.client !== void 0) {
5512
6292
  this.clientName = options.client;
5513
6293
  }
6294
+ if (options.userId !== void 0) {
6295
+ this.defaultUserId = options.userId;
6296
+ }
6297
+ if (options.organizationId !== void 0) {
6298
+ this.defaultOrganizationId = options.organizationId;
6299
+ }
6300
+ if (options.forceNoCache !== void 0) {
6301
+ this.forceNoCacheEnabled = options.forceNoCache;
6302
+ }
5514
6303
  if (options.backend !== void 0) {
5515
6304
  this.backendConfig = toBackendConfig(options.backend);
5516
6305
  }
@@ -5565,6 +6354,9 @@ var AthenaClientBuilderImpl = class {
5565
6354
  url: this.rootUrl,
5566
6355
  key: this.apiKey,
5567
6356
  client: this.clientName,
6357
+ userId: this.defaultUserId,
6358
+ organizationId: this.defaultOrganizationId,
6359
+ forceNoCache: this.forceNoCacheEnabled,
5568
6360
  backend: this.backendConfig,
5569
6361
  headers: this.defaultHeaders,
5570
6362
  db: this.dbUrlOverride ? { url: this.dbUrlOverride } : void 0,
@@ -5608,7 +6400,7 @@ var BOOLEAN_SAFE_OPERATORS = /* @__PURE__ */ new Set([
5608
6400
  "ilike",
5609
6401
  "is"
5610
6402
  ]);
5611
- function isRecord7(value) {
6403
+ function isRecord8(value) {
5612
6404
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
5613
6405
  }
5614
6406
  function isUuidString(value) {
@@ -5621,7 +6413,7 @@ function shouldUseUuidTextComparison(column, value) {
5621
6413
  return typeof value === "string" && isUuidString(value) && isUuidIdentifierColumn(column);
5622
6414
  }
5623
6415
  function isRelationSelectNode(value) {
5624
- return isRecord7(value) && isRecord7(value.select);
6416
+ return isRecord8(value) && isRecord8(value.select);
5625
6417
  }
5626
6418
  function normalizeIdentifier(value, label) {
5627
6419
  const normalized = value.trim();
@@ -5677,7 +6469,7 @@ function compileRelationToken(key, node) {
5677
6469
  return `${prefix}${relationToken}(${nested})`;
5678
6470
  }
5679
6471
  function compileSelectShape(select) {
5680
- if (!isRecord7(select)) {
6472
+ if (!isRecord8(select)) {
5681
6473
  throw new Error("findMany select must be an object");
5682
6474
  }
5683
6475
  const tokens = [];
@@ -5701,7 +6493,7 @@ function compileSelectShape(select) {
5701
6493
  return tokens.join(",");
5702
6494
  }
5703
6495
  function selectShapeUsesRelationSchema(select) {
5704
- if (!isRecord7(select)) {
6496
+ if (!isRecord8(select)) {
5705
6497
  return false;
5706
6498
  }
5707
6499
  for (const rawValue of Object.values(select)) {
@@ -5719,7 +6511,7 @@ function selectShapeUsesRelationSchema(select) {
5719
6511
  }
5720
6512
  function compileColumnWhere(column, input) {
5721
6513
  const normalizedColumn = normalizeIdentifier(column, "where column");
5722
- if (!isRecord7(input)) {
6514
+ if (!isRecord8(input)) {
5723
6515
  return [buildGatewayCondition("eq", normalizedColumn, input)];
5724
6516
  }
5725
6517
  const conditions = [];
@@ -5747,7 +6539,7 @@ function compileColumnWhere(column, input) {
5747
6539
  return conditions;
5748
6540
  }
5749
6541
  function compileBooleanExpressionTerms(clause, label) {
5750
- if (!isRecord7(clause)) {
6542
+ if (!isRecord8(clause)) {
5751
6543
  throw new Error(`findMany where.${label} clauses must be objects`);
5752
6544
  }
5753
6545
  const entries = Object.entries(clause).filter(([, value]) => value !== void 0);
@@ -5756,7 +6548,7 @@ function compileBooleanExpressionTerms(clause, label) {
5756
6548
  }
5757
6549
  const [rawColumn, rawValue] = entries[0];
5758
6550
  const column = normalizeIdentifier(rawColumn, `where.${label} column`);
5759
- if (!isRecord7(rawValue)) {
6551
+ if (!isRecord8(rawValue)) {
5760
6552
  return [`${column}.eq.${stringifyFilterValue(rawValue)}`];
5761
6553
  }
5762
6554
  const operatorEntries = Object.entries(rawValue).filter(([, value]) => value !== void 0);
@@ -5780,7 +6572,7 @@ function compileWhere(where) {
5780
6572
  if (where === void 0) {
5781
6573
  return void 0;
5782
6574
  }
5783
- if (!isRecord7(where)) {
6575
+ if (!isRecord8(where)) {
5784
6576
  throw new Error("findMany where must be an object");
5785
6577
  }
5786
6578
  const conditions = [];
@@ -5830,7 +6622,7 @@ function compileOrderBy(orderBy) {
5830
6622
  if (orderBy === void 0) {
5831
6623
  return void 0;
5832
6624
  }
5833
- if (!isRecord7(orderBy)) {
6625
+ if (!isRecord8(orderBy)) {
5834
6626
  throw new Error("findMany orderBy must be an object");
5835
6627
  }
5836
6628
  if ("column" in orderBy) {
@@ -6005,11 +6797,11 @@ function toFindManyAstOrder(order) {
6005
6797
  ascending: order.direction !== "descending"
6006
6798
  };
6007
6799
  }
6008
- function isRecord8(value) {
6800
+ function isRecord9(value) {
6009
6801
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6010
6802
  }
6011
6803
  function normalizeFindManyAstColumnPredicate(value) {
6012
- if (!isRecord8(value)) {
6804
+ if (!isRecord9(value)) {
6013
6805
  return {
6014
6806
  eq: value
6015
6807
  };
@@ -6033,7 +6825,7 @@ function normalizeFindManyAstBooleanOperand(clause) {
6033
6825
  return normalized;
6034
6826
  }
6035
6827
  function normalizeFindManyAstWhere(where) {
6036
- if (!where || !isRecord8(where)) {
6828
+ if (!where || !isRecord9(where)) {
6037
6829
  return where;
6038
6830
  }
6039
6831
  const normalized = {};
@@ -6047,7 +6839,7 @@ function normalizeFindManyAstWhere(where) {
6047
6839
  );
6048
6840
  continue;
6049
6841
  }
6050
- if (key === "not" && isRecord8(value)) {
6842
+ if (key === "not" && isRecord9(value)) {
6051
6843
  normalized.not = normalizeFindManyAstBooleanOperand(
6052
6844
  value
6053
6845
  );
@@ -6058,7 +6850,7 @@ function normalizeFindManyAstWhere(where) {
6058
6850
  return normalized;
6059
6851
  }
6060
6852
  function predicateRequiresUuidQueryFallback(column, value) {
6061
- if (!isRecord8(value)) {
6853
+ if (!isRecord9(value)) {
6062
6854
  return shouldUseUuidTextComparison(column, value);
6063
6855
  }
6064
6856
  const eqValue = value.eq;
@@ -6076,7 +6868,7 @@ function booleanOperandRequiresUuidQueryFallback(clause) {
6076
6868
  return false;
6077
6869
  }
6078
6870
  function findManyAstWhereRequiresLegacyTransport(where) {
6079
- if (!where || !isRecord8(where)) {
6871
+ if (!where || !isRecord9(where)) {
6080
6872
  return false;
6081
6873
  }
6082
6874
  for (const [key, value] of Object.entries(where)) {
@@ -6091,7 +6883,7 @@ function findManyAstWhereRequiresLegacyTransport(where) {
6091
6883
  }
6092
6884
  continue;
6093
6885
  }
6094
- if (key === "not" && isRecord8(value)) {
6886
+ if (key === "not" && isRecord9(value)) {
6095
6887
  if (booleanOperandRequiresUuidQueryFallback(value)) {
6096
6888
  return true;
6097
6889
  }
@@ -6640,6 +7432,7 @@ function resolveAthenaModelTargetTableName(target, options = {}) {
6640
7432
  var DEFAULT_COLUMNS = "*";
6641
7433
  var SAFE_CAST_PATTERN = /^[a-z_][a-z0-9_]*(?:\[\])?$/i;
6642
7434
  var ATHENA_NORMALIZED_ERROR_KEY = "__athenaNormalizedError";
7435
+ var SDK_NAME4 = "xylex-group/athena";
6643
7436
  function formatResult(response) {
6644
7437
  const result = {
6645
7438
  data: response.data ?? null,
@@ -6716,7 +7509,7 @@ async function executeExperimentalRead(experimental, runner) {
6716
7509
  throw error;
6717
7510
  }
6718
7511
  }
6719
- function isRecord9(value) {
7512
+ function isRecord10(value) {
6720
7513
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6721
7514
  }
6722
7515
  function firstNonEmptyString2(...values) {
@@ -6728,8 +7521,8 @@ function firstNonEmptyString2(...values) {
6728
7521
  return void 0;
6729
7522
  }
6730
7523
  function resolveStructuredErrorPayload2(raw) {
6731
- if (!isRecord9(raw)) return null;
6732
- return isRecord9(raw.error) ? raw.error : raw;
7524
+ if (!isRecord10(raw)) return null;
7525
+ return isRecord10(raw.error) ? raw.error : raw;
6733
7526
  }
6734
7527
  function resolveStructuredErrorDetails(payload, message) {
6735
7528
  if (!payload || !("details" in payload)) {
@@ -6745,7 +7538,7 @@ function resolveStructuredErrorDetails(payload, message) {
6745
7538
  return details;
6746
7539
  }
6747
7540
  function createResultError(response, result, normalized) {
6748
- const rawRecord = isRecord9(response.raw) ? response.raw : null;
7541
+ const rawRecord = isRecord10(response.raw) ? response.raw : null;
6749
7542
  const payload = resolveStructuredErrorPayload2(response.raw);
6750
7543
  const message = firstNonEmptyString2(
6751
7544
  response.error,
@@ -6808,6 +7601,43 @@ function asAthenaJsonObject(value) {
6808
7601
  function asAthenaJsonObjectArray(values) {
6809
7602
  return values;
6810
7603
  }
7604
+ function parseArbitraryResponseBody(rawText, contentType) {
7605
+ if (!rawText) {
7606
+ return null;
7607
+ }
7608
+ const contentTypeSuggestsJson = contentType?.toLowerCase().includes("application/json") ?? false;
7609
+ const looksJson = contentTypeSuggestsJson || rawText.startsWith("{") || rawText.startsWith("[");
7610
+ if (!looksJson) {
7611
+ return rawText;
7612
+ }
7613
+ try {
7614
+ return JSON.parse(rawText);
7615
+ } catch {
7616
+ return rawText;
7617
+ }
7618
+ }
7619
+ function toRequestQueryString(query) {
7620
+ if (!query) {
7621
+ return "";
7622
+ }
7623
+ const params = new URLSearchParams();
7624
+ for (const [key, value] of Object.entries(query)) {
7625
+ if (value === void 0 || value === null) {
7626
+ continue;
7627
+ }
7628
+ if (Array.isArray(value)) {
7629
+ for (const item of value) {
7630
+ if (item !== void 0 && item !== null) {
7631
+ params.append(key, String(item));
7632
+ }
7633
+ }
7634
+ continue;
7635
+ }
7636
+ params.set(key, String(value));
7637
+ }
7638
+ const encoded = params.toString();
7639
+ return encoded ? `?${encoded}` : "";
7640
+ }
6811
7641
  function normalizeSelectColumnsInput(columns) {
6812
7642
  if (columns === void 0) {
6813
7643
  return void 0;
@@ -8107,6 +8937,85 @@ function createQueryBuilder(client, formatGatewayResult, experimental, tracer) {
8107
8937
  );
8108
8938
  };
8109
8939
  }
8940
+ var ATHENA_ENV_URL_KEYS = ["ATHENA_URL", "NEXT_PUBLIC_ATHENA_URL"];
8941
+ var ATHENA_ENV_GATEWAY_URL_KEYS = [
8942
+ "ATHENA_DB_URL",
8943
+ "ATHENA_GATEWAY_URL",
8944
+ "NEXT_PUBLIC_ATHENA_DB_API_URL"
8945
+ ];
8946
+ var ATHENA_ENV_AUTH_URL_KEYS = ["ATHENA_AUTH_URL", "NEXT_PUBLIC_ATHENA_AUTH_URL"];
8947
+ var ATHENA_ENV_CHAT_URL_KEYS = ["ATHENA_CHAT_URL", "NEXT_PUBLIC_ATHENA_CHAT_URL"];
8948
+ var ATHENA_ENV_CHAT_WS_URL_KEYS = ["ATHENA_CHAT_WS_URL", "NEXT_PUBLIC_ATHENA_CHAT_WS_URL"];
8949
+ var ATHENA_ENV_STORAGE_URL_KEYS = ["ATHENA_STORAGE_URL", "NEXT_PUBLIC_ATHENA_STORAGE_URL"];
8950
+ var ATHENA_ENV_KEY_KEYS = [
8951
+ "ATHENA_API_KEY",
8952
+ "NEXT_PUBLIC_ATHENA_API_KEY",
8953
+ "ATHENA_GATEWAY_API_KEY",
8954
+ "X_API_KEY"
8955
+ ];
8956
+ var ATHENA_ENV_CLIENT_KEYS = ["ATHENA_CLIENT", "NEXT_PUBLIC_ATHENA_CLIENT"];
8957
+ function normalizeOptionalString(value) {
8958
+ if (typeof value !== "string") {
8959
+ return void 0;
8960
+ }
8961
+ const normalizedValue = value.trim();
8962
+ return normalizedValue ? normalizedValue : void 0;
8963
+ }
8964
+ function readFirstEnvValue(env, keys) {
8965
+ for (const key of keys) {
8966
+ const value = normalizeOptionalString(env[key]);
8967
+ if (value) {
8968
+ return value;
8969
+ }
8970
+ }
8971
+ return void 0;
8972
+ }
8973
+ function readHeaderBagValue(headers, targetKey) {
8974
+ if (!headers) {
8975
+ return void 0;
8976
+ }
8977
+ if (typeof headers.get === "function") {
8978
+ return normalizeOptionalString(headers.get(targetKey));
8979
+ }
8980
+ const normalizedTargetKey = targetKey.toLowerCase();
8981
+ for (const [key, value] of Object.entries(headers)) {
8982
+ if (key.toLowerCase() !== normalizedTargetKey) {
8983
+ continue;
8984
+ }
8985
+ if (typeof value === "string") {
8986
+ return normalizeOptionalString(value);
8987
+ }
8988
+ return void 0;
8989
+ }
8990
+ return void 0;
8991
+ }
8992
+ function resolveSessionContextOptions(session, options) {
8993
+ const sessionToken = normalizeOptionalString(session?.session?.token);
8994
+ const requestCookie = readHeaderBagValue(options?.requestHeaders, "cookie") ?? readHeaderBagValue(options?.headers, "cookie");
8995
+ const authInput = options?.auth;
8996
+ const resolvedUserId = options?.userId !== void 0 ? options.userId : session?.user?.id;
8997
+ const resolvedOrganizationId = options?.organizationId !== void 0 ? options.organizationId : session?.session?.activeOrganizationId;
8998
+ const resolvedBearerToken = authInput?.bearerToken !== void 0 ? authInput.bearerToken : sessionToken;
8999
+ const resolvedSessionToken = authInput?.sessionToken !== void 0 ? authInput.sessionToken : sessionToken;
9000
+ const resolvedCookie = authInput?.cookie !== void 0 ? authInput.cookie : requestCookie;
9001
+ const auth = authInput !== void 0 || resolvedBearerToken !== void 0 || resolvedSessionToken !== void 0 || resolvedCookie !== void 0 ? {
9002
+ ...authInput ?? {},
9003
+ ...resolvedBearerToken !== void 0 ? { bearerToken: resolvedBearerToken } : {},
9004
+ ...resolvedSessionToken !== void 0 ? { sessionToken: resolvedSessionToken } : {},
9005
+ ...resolvedCookie !== void 0 ? { cookie: resolvedCookie } : {},
9006
+ headers: authInput?.headers ? { ...authInput.headers } : void 0
9007
+ } : void 0;
9008
+ if (resolvedUserId === void 0 && resolvedOrganizationId === void 0 && options?.forceNoCache === void 0 && !options?.headers && !auth) {
9009
+ return void 0;
9010
+ }
9011
+ return {
9012
+ userId: resolvedUserId,
9013
+ organizationId: resolvedOrganizationId,
9014
+ forceNoCache: options?.forceNoCache,
9015
+ headers: options?.headers ? { ...options.headers } : void 0,
9016
+ auth
9017
+ };
9018
+ }
8110
9019
  function resolveClientServiceBaseUrl(value, label) {
8111
9020
  if (value === void 0 || value === null) {
8112
9021
  return void 0;
@@ -8117,6 +9026,15 @@ function appendServicePath(baseUrl, segment) {
8117
9026
  const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(baseUrl, { label: "Athena public base URL" });
8118
9027
  return `${normalizedBaseUrl}/${segment.replace(/^\/+/, "")}`;
8119
9028
  }
9029
+ function appendRealtimeGatewayPath(baseUrl) {
9030
+ const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(baseUrl, { label: "Athena public base URL" });
9031
+ const wsUrl = new URL(normalizedBaseUrl);
9032
+ wsUrl.protocol = wsUrl.protocol === "https:" ? "wss:" : "ws:";
9033
+ wsUrl.pathname = `${wsUrl.pathname.replace(/\/+$/, "")}/wss/gateway`;
9034
+ wsUrl.search = "";
9035
+ wsUrl.hash = "";
9036
+ return wsUrl.toString();
9037
+ }
8120
9038
  function resolveServiceUrlOverride(value, label) {
8121
9039
  return resolveClientServiceBaseUrl(value, label);
8122
9040
  }
@@ -8125,6 +9043,8 @@ function resolveServiceUrls(config) {
8125
9043
  return {
8126
9044
  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),
8127
9045
  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),
9046
+ chatUrl: resolveServiceUrlOverride(config.chat?.url, "Athena chat base URL") ?? resolveServiceUrlOverride(config.chatUrl, "Athena chat base URL") ?? (baseUrl ? appendServicePath(baseUrl, "chat") : void 0),
9047
+ chatWsUrl: normalizeOptionalString(config.chat?.wsUrl) ?? normalizeOptionalString(config.chatWsUrl) ?? (baseUrl ? appendRealtimeGatewayPath(baseUrl) : void 0),
8128
9048
  storageUrl: resolveServiceUrlOverride(config.storage?.url, "Athena storage base URL") ?? resolveServiceUrlOverride(config.storageUrl, "Athena storage base URL") ?? (baseUrl ? appendServicePath(baseUrl, "storage") : void 0)
8129
9049
  };
8130
9050
  }
@@ -8149,6 +9069,89 @@ function resolveRequiredClientApiKey(value) {
8149
9069
  }
8150
9070
  return normalizedValue;
8151
9071
  }
9072
+ function hasHeaderIgnoreCase(headers, targetKey) {
9073
+ const normalizedTargetKey = targetKey.toLowerCase();
9074
+ return Object.keys(headers).some((key) => key.toLowerCase() === normalizedTargetKey);
9075
+ }
9076
+ function mergeClientHeaders(current, next) {
9077
+ if (!current && !next) {
9078
+ return void 0;
9079
+ }
9080
+ return {
9081
+ ...current ?? {},
9082
+ ...next ?? {}
9083
+ };
9084
+ }
9085
+ function mergeDefinedObject(current, next) {
9086
+ if (!current && !next) {
9087
+ return void 0;
9088
+ }
9089
+ const merged = {
9090
+ ...current ?? {}
9091
+ };
9092
+ const mutableMerged = merged;
9093
+ for (const [key, value] of Object.entries(next ?? {})) {
9094
+ if (value !== void 0) {
9095
+ mutableMerged[key] = value;
9096
+ }
9097
+ }
9098
+ return merged;
9099
+ }
9100
+ function mergeAuthClientOptions(current, next) {
9101
+ const merged = mergeDefinedObject(current, next);
9102
+ if (!merged) {
9103
+ return void 0;
9104
+ }
9105
+ const mergedHeaders = mergeClientHeaders(current?.headers, next?.headers);
9106
+ if (mergedHeaders) {
9107
+ merged.headers = mergedHeaders;
9108
+ }
9109
+ return merged;
9110
+ }
9111
+ function mergeServiceUrlOverrides(current, next) {
9112
+ return mergeDefinedObject(current, next);
9113
+ }
9114
+ function toClientContextOverrides(context) {
9115
+ if (!context) {
9116
+ return void 0;
9117
+ }
9118
+ return {
9119
+ userId: context.userId,
9120
+ organizationId: context.organizationId,
9121
+ forceNoCache: context.forceNoCache,
9122
+ headers: context.headers,
9123
+ auth: context.auth ? {
9124
+ ...context.auth,
9125
+ headers: context.auth.headers ? { ...context.auth.headers } : void 0
9126
+ } : void 0
9127
+ };
9128
+ }
9129
+ function mergeClientOverrideOptions(base, overrides) {
9130
+ if (!overrides) {
9131
+ return {
9132
+ ...base,
9133
+ headers: base.headers ? { ...base.headers } : void 0,
9134
+ auth: base.auth ? {
9135
+ ...base.auth,
9136
+ headers: base.auth.headers ? { ...base.auth.headers } : void 0
9137
+ } : void 0,
9138
+ db: base.db ? { ...base.db } : void 0,
9139
+ gateway: base.gateway ? { ...base.gateway } : void 0,
9140
+ chat: base.chat ? { ...base.chat } : void 0,
9141
+ storage: base.storage ? { ...base.storage } : void 0
9142
+ };
9143
+ }
9144
+ const merged = mergeDefinedObject(base, overrides) ?? { ...base };
9145
+ return {
9146
+ ...merged,
9147
+ headers: mergeClientHeaders(base.headers, overrides.headers),
9148
+ auth: mergeAuthClientOptions(base.auth, overrides.auth),
9149
+ db: mergeServiceUrlOverrides(base.db, overrides.db),
9150
+ gateway: mergeServiceUrlOverrides(base.gateway, overrides.gateway),
9151
+ chat: mergeServiceUrlOverrides(base.chat, overrides.chat),
9152
+ storage: mergeServiceUrlOverrides(base.storage, overrides.storage)
9153
+ };
9154
+ }
8152
9155
  function normalizeAuthClientConfig(auth, defaultBaseUrl) {
8153
9156
  if (!auth && defaultBaseUrl === void 0) {
8154
9157
  return void 0;
@@ -8158,6 +9161,8 @@ function normalizeAuthClientConfig(auth, defaultBaseUrl) {
8158
9161
  baseUrl,
8159
9162
  apiKey,
8160
9163
  bearerToken,
9164
+ cookie,
9165
+ sessionToken,
8161
9166
  ...rest
8162
9167
  } = auth ?? {};
8163
9168
  const normalized = {
@@ -8176,6 +9181,12 @@ function normalizeAuthClientConfig(auth, defaultBaseUrl) {
8176
9181
  if (typeof bearerToken === "string") {
8177
9182
  normalized.bearerToken = bearerToken;
8178
9183
  }
9184
+ if (typeof cookie === "string") {
9185
+ normalized.cookie = cookie;
9186
+ }
9187
+ if (typeof sessionToken === "string") {
9188
+ normalized.sessionToken = sessionToken;
9189
+ }
8179
9190
  return normalized;
8180
9191
  }
8181
9192
  function resolveCreateClientConfig(config) {
@@ -8189,31 +9200,53 @@ function resolveCreateClientConfig(config) {
8189
9200
  baseUrl: resolvedUrls.dbUrl,
8190
9201
  apiKey: resolveRequiredClientApiKey(config.key),
8191
9202
  client: resolveOptionalClientName(config.client),
9203
+ userId: config.userId,
9204
+ organizationId: config.organizationId,
9205
+ forceNoCache: config.forceNoCache,
8192
9206
  backend: toBackendConfig(config.backend),
8193
9207
  headers: config.headers,
8194
9208
  auth: config.auth,
8195
9209
  authUrl: resolvedUrls.authUrl,
9210
+ chat: config.chat,
9211
+ chatUrl: resolvedUrls.chatUrl,
9212
+ chatWsUrl: resolvedUrls.chatWsUrl,
8196
9213
  storageUrl: resolvedUrls.storageUrl,
8197
9214
  experimental: config.experimental
8198
9215
  };
8199
9216
  }
8200
- function createClientFromConfig(config) {
9217
+ function createClientFromInput(sourceConfig) {
9218
+ return createClientFromConfig(resolveCreateClientConfig(sourceConfig), sourceConfig);
9219
+ }
9220
+ function createClientFromConfig(config, sourceConfig) {
9221
+ const normalizedAuthConfig = normalizeAuthClientConfig(config.auth, config.authUrl);
8201
9222
  const gatewayHeaders = {
8202
9223
  ...config.headers ?? {}
8203
9224
  };
8204
- if (config.auth?.bearerToken && gatewayHeaders["X-Athena-Auth-Bearer-Token"] === void 0 && gatewayHeaders["x-athena-auth-bearer-token"] === void 0) {
8205
- gatewayHeaders["X-Athena-Auth-Bearer-Token"] = config.auth.bearerToken;
9225
+ if (normalizedAuthConfig?.bearerToken && !hasHeaderIgnoreCase(gatewayHeaders, "X-Athena-Auth-Bearer-Token")) {
9226
+ gatewayHeaders["X-Athena-Auth-Bearer-Token"] = normalizedAuthConfig.bearerToken;
9227
+ }
9228
+ if (normalizedAuthConfig?.cookie && !hasHeaderIgnoreCase(gatewayHeaders, "Cookie")) {
9229
+ gatewayHeaders.Cookie = normalizedAuthConfig.cookie;
9230
+ }
9231
+ if (normalizedAuthConfig?.sessionToken && !hasHeaderIgnoreCase(gatewayHeaders, "X-Athena-Auth-Session-Token")) {
9232
+ gatewayHeaders["X-Athena-Auth-Session-Token"] = normalizedAuthConfig.sessionToken;
8206
9233
  }
8207
9234
  const gateway = createAthenaGatewayClient({
8208
9235
  baseUrl: config.baseUrl,
8209
9236
  apiKey: config.apiKey,
8210
9237
  client: config.client,
9238
+ userId: config.userId,
9239
+ organizationId: config.organizationId,
9240
+ forceNoCache: config.forceNoCache,
8211
9241
  backend: config.backend,
8212
9242
  headers: gatewayHeaders
8213
9243
  });
8214
9244
  const formatGatewayResult = createResultFormatter(config.experimental);
8215
9245
  const queryTracer = createQueryTracer(config.experimental);
8216
- const auth = createAuthClient(normalizeAuthClientConfig(config.auth, config.authUrl));
9246
+ const auth = createAuthClient({
9247
+ ...normalizedAuthConfig ?? {},
9248
+ ...config.forceNoCache ? { forceNoCache: true } : {}
9249
+ });
8217
9250
  function from(tableOrModel, options) {
8218
9251
  if (isAthenaModelTarget(tableOrModel)) {
8219
9252
  if (options?.schema !== void 0) {
@@ -8261,17 +9294,160 @@ function createClientFromConfig(config) {
8261
9294
  queryTracer
8262
9295
  );
8263
9296
  const db = createDbModule({ from, rpc, query });
9297
+ const chat = createChatModule({
9298
+ baseUrl: config.chatUrl,
9299
+ apiKey: config.apiKey,
9300
+ client: config.client,
9301
+ headers: config.headers,
9302
+ bearerToken: normalizedAuthConfig?.bearerToken,
9303
+ cookie: normalizedAuthConfig?.cookie,
9304
+ sessionToken: normalizedAuthConfig?.sessionToken,
9305
+ forceNoCache: config.forceNoCache,
9306
+ wsUrl: config.chatWsUrl,
9307
+ webSocketFactory: config.chat?.webSocketFactory ?? void 0
9308
+ });
9309
+ const request2 = async (options) => {
9310
+ const method = options.method ?? "GET";
9311
+ const responseType = options.responseType ?? "json";
9312
+ const service = options.service ?? "db";
9313
+ const baseUrlByService = {
9314
+ db: config.baseUrl,
9315
+ auth: config.authUrl,
9316
+ chat: config.chatUrl,
9317
+ storage: config.storageUrl
9318
+ };
9319
+ const resolvedBaseUrl = options.url ?? baseUrlByService[service];
9320
+ if (!resolvedBaseUrl) {
9321
+ throw new Error(
9322
+ `Athena ${service} base URL is not configured. Pass createClient({ url }) for unified routing or set the service-specific URL first.`
9323
+ );
9324
+ }
9325
+ const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(resolvedBaseUrl, {
9326
+ label: `Athena ${service} base URL`
9327
+ });
9328
+ const normalizedPath = options.url ? "" : (() => {
9329
+ const path = options.path?.trim();
9330
+ if (!path) {
9331
+ throw new Error("client.request(...) requires either an absolute url or a non-empty path.");
9332
+ }
9333
+ return path.startsWith("/") ? path : `/${path}`;
9334
+ })();
9335
+ const targetUrl = options.url ? `${normalizedBaseUrl}${toRequestQueryString(options.query)}` : `${normalizedBaseUrl}${normalizedPath}${toRequestQueryString(options.query)}`;
9336
+ const headers = {
9337
+ "X-Athena-Sdk": buildSdkHeaderValue(SDK_NAME4),
9338
+ ...config.headers ?? {},
9339
+ ...options.headers ?? {}
9340
+ };
9341
+ if (service !== "auth") {
9342
+ headers.apikey = headers.apikey ?? config.apiKey;
9343
+ headers["x-api-key"] = headers["x-api-key"] ?? config.apiKey;
9344
+ if (config.client && !hasHeaderIgnoreCase(headers, "X-Athena-Client")) {
9345
+ headers["X-Athena-Client"] = config.client;
9346
+ }
9347
+ if (config.userId && !hasHeaderIgnoreCase(headers, "X-User-Id")) {
9348
+ headers["X-User-Id"] = config.userId;
9349
+ }
9350
+ if (config.organizationId && !hasHeaderIgnoreCase(headers, "X-Organization-Id")) {
9351
+ headers["X-Organization-Id"] = config.organizationId;
9352
+ }
9353
+ if (normalizedAuthConfig?.sessionToken && !hasHeaderIgnoreCase(headers, "X-Athena-Auth-Session-Token")) {
9354
+ headers["X-Athena-Auth-Session-Token"] = normalizedAuthConfig.sessionToken;
9355
+ }
9356
+ if (normalizedAuthConfig?.bearerToken && !hasHeaderIgnoreCase(headers, "X-Athena-Auth-Bearer-Token")) {
9357
+ headers["X-Athena-Auth-Bearer-Token"] = normalizedAuthConfig.bearerToken;
9358
+ }
9359
+ if (normalizedAuthConfig?.cookie && !hasHeaderIgnoreCase(headers, "Cookie")) {
9360
+ headers.Cookie = normalizedAuthConfig.cookie;
9361
+ }
9362
+ } else {
9363
+ const authApiKey = normalizedAuthConfig?.apiKey ?? config.apiKey;
9364
+ if (authApiKey && !hasHeaderIgnoreCase(headers, "x-api-key")) {
9365
+ headers.apikey = headers.apikey ?? authApiKey;
9366
+ headers["x-api-key"] = headers["x-api-key"] ?? authApiKey;
9367
+ }
9368
+ if (normalizedAuthConfig?.bearerToken && !hasHeaderIgnoreCase(headers, "Authorization")) {
9369
+ headers.Authorization = `Bearer ${normalizedAuthConfig.bearerToken}`;
9370
+ }
9371
+ if (normalizedAuthConfig?.cookie && !hasHeaderIgnoreCase(headers, "Cookie")) {
9372
+ headers.Cookie = normalizedAuthConfig.cookie;
9373
+ }
9374
+ if (normalizedAuthConfig?.sessionToken && !hasHeaderIgnoreCase(headers, "X-Athena-Auth-Session-Token")) {
9375
+ headers["X-Athena-Auth-Session-Token"] = normalizedAuthConfig.sessionToken;
9376
+ }
9377
+ }
9378
+ 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";
9379
+ if (shouldSendJsonBody && !hasHeaderIgnoreCase(headers, "Content-Type")) {
9380
+ headers["Content-Type"] = "application/json";
9381
+ }
9382
+ const response = await fetch(targetUrl, {
9383
+ method,
9384
+ headers,
9385
+ body: options.body === void 0 || options.body === null ? void 0 : shouldSendJsonBody ? JSON.stringify(options.body) : options.body,
9386
+ signal: options.signal,
9387
+ credentials: options.credentials
9388
+ });
9389
+ if (responseType === "response") {
9390
+ return {
9391
+ ok: response.ok,
9392
+ status: response.status,
9393
+ statusText: response.statusText,
9394
+ headers: response.headers,
9395
+ data: null,
9396
+ raw: response
9397
+ };
9398
+ }
9399
+ const rawText = await response.text();
9400
+ const parsed = responseType === "text" ? rawText : parseArbitraryResponseBody(rawText, response.headers.get("content-type"));
9401
+ return {
9402
+ ok: response.ok,
9403
+ status: response.status,
9404
+ statusText: response.statusText,
9405
+ headers: response.headers,
9406
+ data: parsed,
9407
+ raw: response
9408
+ };
9409
+ };
9410
+ const withContext = (context) => createClientFromInput(
9411
+ mergeClientOverrideOptions(sourceConfig, toClientContextOverrides(context))
9412
+ );
9413
+ const withSession = (session, options) => createClientFromInput(
9414
+ mergeClientOverrideOptions(
9415
+ sourceConfig,
9416
+ toClientContextOverrides(resolveSessionContextOptions(session, options))
9417
+ )
9418
+ );
9419
+ const authWithOptions = (options) => createClientFromInput(mergeClientOverrideOptions(sourceConfig, options));
8264
9420
  const sdkClient = {
8265
9421
  from,
8266
9422
  db,
8267
9423
  rpc,
8268
9424
  query,
9425
+ request: request2,
8269
9426
  verifyConnection: gateway.verifyConnection,
8270
- auth: auth.auth
9427
+ auth: auth.auth,
9428
+ chat,
9429
+ withContext,
9430
+ withSession,
9431
+ withOptions: authWithOptions
8271
9432
  };
8272
9433
  if (config.experimental?.athenaStorageBackend) {
9434
+ const storageWithContext = (context) => createClientFromInput(
9435
+ mergeClientOverrideOptions(sourceConfig, toClientContextOverrides(context))
9436
+ );
9437
+ const storageWithSession = (session, options) => createClientFromInput(
9438
+ mergeClientOverrideOptions(
9439
+ sourceConfig,
9440
+ toClientContextOverrides(resolveSessionContextOptions(session, options))
9441
+ )
9442
+ );
9443
+ const storageWithOptions = (options) => createClientFromInput(
9444
+ mergeClientOverrideOptions(sourceConfig, options)
9445
+ );
8273
9446
  const storageClient = {
8274
9447
  ...sdkClient,
9448
+ withContext: storageWithContext,
9449
+ withSession: storageWithSession,
9450
+ withOptions: storageWithOptions,
8275
9451
  storage: createStorageModule(gateway, {
8276
9452
  ...config.experimental.storage,
8277
9453
  ...config.storageUrl ? {
@@ -8287,38 +9463,46 @@ function createClientFromConfig(config) {
8287
9463
  var AthenaClient = class {
8288
9464
  /** Create a fluent builder for a strongly-typed Athena SDK client. */
8289
9465
  static builder() {
8290
- return createAthenaClientBuilder((config) => createClientFromConfig(resolveCreateClientConfig(config)));
8291
- }
8292
- /** Build a client from process environment variables. */
8293
- static fromEnvironment() {
8294
- const url = process.env.ATHENA_URL;
8295
- const gatewayUrl = process.env.ATHENA_DB_URL ?? process.env.ATHENA_GATEWAY_URL;
8296
- const authUrl = process.env.ATHENA_AUTH_URL;
8297
- const storageUrl = process.env.ATHENA_STORAGE_URL;
8298
- const key = process.env.ATHENA_API_KEY ?? process.env.ATHENA_GATEWAY_API_KEY;
9466
+ return createAthenaClientBuilder((config) => createClientFromInput(config));
9467
+ }
9468
+ static fromEnvironment(options = {}) {
9469
+ const env = options.env ?? process.env;
9470
+ const url = options.url ?? readFirstEnvValue(env, ATHENA_ENV_URL_KEYS);
9471
+ const gatewayUrl = options.gatewayUrl ?? readFirstEnvValue(env, ATHENA_ENV_GATEWAY_URL_KEYS);
9472
+ const authUrl = options.authUrl ?? readFirstEnvValue(env, ATHENA_ENV_AUTH_URL_KEYS);
9473
+ const chatUrl = options.chatUrl ?? readFirstEnvValue(env, ATHENA_ENV_CHAT_URL_KEYS);
9474
+ const chatWsUrl = options.chatWsUrl ?? readFirstEnvValue(env, ATHENA_ENV_CHAT_WS_URL_KEYS);
9475
+ const storageUrl = options.storageUrl ?? readFirstEnvValue(env, ATHENA_ENV_STORAGE_URL_KEYS);
9476
+ const key = options.key ?? readFirstEnvValue(env, ATHENA_ENV_KEY_KEYS);
9477
+ const client = options.client ?? readFirstEnvValue(env, ATHENA_ENV_CLIENT_KEYS);
8299
9478
  if (!url && !gatewayUrl || !key) {
8300
9479
  throw new Error(
8301
- "ATHENA_API_KEY plus ATHENA_URL or ATHENA_GATEWAY_URL (optionally ATHENA_DB_URL, ATHENA_AUTH_URL, ATHENA_STORAGE_URL) are required"
9480
+ "AthenaClient.fromEnvironment() requires an API key plus a public or gateway URL. Supported aliases include ATHENA_API_KEY, NEXT_PUBLIC_ATHENA_API_KEY, ATHENA_GATEWAY_API_KEY, X_API_KEY, ATHENA_URL, NEXT_PUBLIC_ATHENA_URL, ATHENA_GATEWAY_URL, and ATHENA_DB_URL."
8302
9481
  );
8303
9482
  }
9483
+ const { env: _env, ...clientOptions } = options;
8304
9484
  return createClient({
9485
+ ...clientOptions,
8305
9486
  url,
8306
9487
  gatewayUrl,
8307
9488
  authUrl,
9489
+ chatUrl,
9490
+ chatWsUrl,
8308
9491
  storageUrl,
8309
- key
9492
+ key,
9493
+ client
8310
9494
  });
8311
9495
  }
8312
9496
  };
8313
9497
  function createClient(configOrUrl, apiKey, options) {
8314
9498
  if (typeof configOrUrl === "string" || configOrUrl === null || configOrUrl === void 0) {
8315
- return createClientFromConfig(resolveCreateClientConfig({
9499
+ return createClientFromInput({
8316
9500
  url: configOrUrl,
8317
9501
  key: apiKey ?? "",
8318
9502
  ...options
8319
- }));
9503
+ });
8320
9504
  }
8321
- return createClientFromConfig(resolveCreateClientConfig(configOrUrl));
9505
+ return createClientFromInput(configOrUrl);
8322
9506
  }
8323
9507
 
8324
9508
  // src/gateway/types.ts
@@ -8349,7 +9533,7 @@ function resolveNullishValue(mode) {
8349
9533
  if (mode === "null") return null;
8350
9534
  return "";
8351
9535
  }
8352
- function isRecord10(value) {
9536
+ function isRecord11(value) {
8353
9537
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
8354
9538
  }
8355
9539
  function isNullableColumn(model, key) {
@@ -8358,7 +9542,7 @@ function isNullableColumn(model, key) {
8358
9542
  }
8359
9543
  function toModelFormDefaults(model, values, options) {
8360
9544
  const source = values;
8361
- if (!isRecord10(source)) {
9545
+ if (!isRecord11(source)) {
8362
9546
  return {};
8363
9547
  }
8364
9548
  const mode = options?.nullishMode ?? "empty-string";
@@ -8684,6 +9868,9 @@ function createColumnsBuilder(name, mappedName, schemaName, columns) {
8684
9868
  resolveTableTarget(name, mappedName, normalizedSchemaName);
8685
9869
  return createColumnsBuilder(name, mappedName, normalizedSchemaName, columns);
8686
9870
  },
9871
+ withoutPrimaryKey() {
9872
+ return finalizeTable(name, mappedName, schemaName, columns, []);
9873
+ },
8687
9874
  primaryKey(...keys) {
8688
9875
  return finalizeTable(name, mappedName, schemaName, columns, keys);
8689
9876
  }
@@ -8735,6 +9922,59 @@ var TenantHeaderMapper = class {
8735
9922
  return Object.keys(headers).length > 0 ? headers : void 0;
8736
9923
  }
8737
9924
  };
9925
+ function normalizeOptionalString2(value) {
9926
+ if (typeof value !== "string") {
9927
+ return void 0;
9928
+ }
9929
+ const normalizedValue = value.trim();
9930
+ return normalizedValue ? normalizedValue : void 0;
9931
+ }
9932
+ function readHeaderBagValue2(headers, targetKey) {
9933
+ if (!headers) {
9934
+ return void 0;
9935
+ }
9936
+ if (typeof headers.get === "function") {
9937
+ return normalizeOptionalString2(headers.get(targetKey));
9938
+ }
9939
+ const normalizedTargetKey = targetKey.toLowerCase();
9940
+ for (const [key, value] of Object.entries(headers)) {
9941
+ if (key.toLowerCase() !== normalizedTargetKey) {
9942
+ continue;
9943
+ }
9944
+ if (typeof value === "string") {
9945
+ return normalizeOptionalString2(value);
9946
+ }
9947
+ return void 0;
9948
+ }
9949
+ return void 0;
9950
+ }
9951
+ function resolveSessionContextOptions2(session, options) {
9952
+ const sessionToken = normalizeOptionalString2(session?.session?.token);
9953
+ const requestCookie = readHeaderBagValue2(options?.requestHeaders, "cookie") ?? readHeaderBagValue2(options?.headers, "cookie");
9954
+ const authInput = options?.auth;
9955
+ const resolvedUserId = options?.userId !== void 0 ? options.userId : session?.user?.id;
9956
+ const resolvedOrganizationId = options?.organizationId !== void 0 ? options.organizationId : session?.session?.activeOrganizationId;
9957
+ const resolvedBearerToken = authInput?.bearerToken !== void 0 ? authInput.bearerToken : sessionToken;
9958
+ const resolvedSessionToken = authInput?.sessionToken !== void 0 ? authInput.sessionToken : sessionToken;
9959
+ const resolvedCookie = authInput?.cookie !== void 0 ? authInput.cookie : requestCookie;
9960
+ const auth = authInput !== void 0 || resolvedBearerToken !== void 0 || resolvedSessionToken !== void 0 || resolvedCookie !== void 0 ? {
9961
+ ...authInput ?? {},
9962
+ ...resolvedBearerToken !== void 0 ? { bearerToken: resolvedBearerToken } : {},
9963
+ ...resolvedSessionToken !== void 0 ? { sessionToken: resolvedSessionToken } : {},
9964
+ ...resolvedCookie !== void 0 ? { cookie: resolvedCookie } : {},
9965
+ headers: authInput?.headers ? { ...authInput.headers } : void 0
9966
+ } : void 0;
9967
+ if (resolvedUserId === void 0 && resolvedOrganizationId === void 0 && options?.forceNoCache === void 0 && !options?.headers && !auth) {
9968
+ return void 0;
9969
+ }
9970
+ return {
9971
+ userId: resolvedUserId,
9972
+ organizationId: resolvedOrganizationId,
9973
+ forceNoCache: options?.forceNoCache,
9974
+ headers: options?.headers ? { ...options.headers } : void 0,
9975
+ auth
9976
+ };
9977
+ }
8738
9978
  var RegistryNavigator = class {
8739
9979
  constructor(registry) {
8740
9980
  this.registry = registry;
@@ -8786,12 +10026,22 @@ var TypedAthenaClientImpl = class _TypedAthenaClientImpl {
8786
10026
  backend: input.options?.backend,
8787
10027
  client: input.options?.client,
8788
10028
  headers: input.options?.headers,
10029
+ forceNoCache: input.options?.forceNoCache,
10030
+ userId: input.options?.userId,
10031
+ organizationId: input.options?.organizationId,
10032
+ auth: input.options?.auth,
10033
+ tenantKeyMap,
10034
+ tenantContext,
8789
10035
  experimental: input.options?.experimental
8790
10036
  };
8791
10037
  this.baseClient = createClient(this.url, this.apiKey, {
8792
10038
  backend: this.clientOptions.backend,
8793
10039
  client: this.clientOptions.client,
8794
10040
  headers: this.tenantHeaderMapper.apply(this.clientOptions.headers, tenantContext),
10041
+ forceNoCache: this.clientOptions.forceNoCache,
10042
+ userId: this.clientOptions.userId,
10043
+ organizationId: this.clientOptions.organizationId,
10044
+ auth: this.clientOptions.auth,
8795
10045
  experimental: this.clientOptions.experimental
8796
10046
  });
8797
10047
  this.db = this.baseClient.db;
@@ -8806,9 +10056,46 @@ var TypedAthenaClientImpl = class _TypedAthenaClientImpl {
8806
10056
  query(query, options) {
8807
10057
  return this.baseClient.query(query, options);
8808
10058
  }
10059
+ request(options) {
10060
+ return this.baseClient.request(options);
10061
+ }
8809
10062
  verifyConnection(options) {
8810
10063
  return this.baseClient.verifyConnection(options);
8811
10064
  }
10065
+ withContext(context) {
10066
+ const headers = {
10067
+ ...this.clientOptions.headers ?? {},
10068
+ ...context?.headers ?? {}
10069
+ };
10070
+ const auth = this.clientOptions.auth || context?.auth ? {
10071
+ ...this.clientOptions.auth ?? {},
10072
+ ...context?.auth ?? {},
10073
+ headers: this.clientOptions.auth?.headers || context?.auth?.headers ? {
10074
+ ...this.clientOptions.auth?.headers ?? {},
10075
+ ...context?.auth?.headers ?? {}
10076
+ } : void 0
10077
+ } : void 0;
10078
+ return new _TypedAthenaClientImpl({
10079
+ registry: this.registry,
10080
+ url: this.url,
10081
+ apiKey: this.apiKey,
10082
+ options: {
10083
+ ...this.clientOptions,
10084
+ headers: Object.keys(headers).length > 0 ? headers : void 0,
10085
+ auth,
10086
+ tenantKeyMap: this.tenantKeyMap,
10087
+ tenantContext: {
10088
+ ...this.tenantContext
10089
+ },
10090
+ ...context?.userId !== void 0 ? { userId: context.userId } : {},
10091
+ ...context?.organizationId !== void 0 ? { organizationId: context.organizationId } : {},
10092
+ ...context?.forceNoCache !== void 0 ? { forceNoCache: context.forceNoCache } : {}
10093
+ }
10094
+ });
10095
+ }
10096
+ withSession(session, options) {
10097
+ return this.withContext(resolveSessionContextOptions2(session, options));
10098
+ }
8812
10099
  withTenantContext(context) {
8813
10100
  return new _TypedAthenaClientImpl({
8814
10101
  registry: this.registry,
@@ -9304,6 +10591,77 @@ function resolveProviderSchemas(providerConfig) {
9304
10591
  return [...DEFAULT_POSTGRES_SCHEMAS];
9305
10592
  }
9306
10593
 
10594
+ // src/generator/table-selection.ts
10595
+ function normalizeTableSelector(value) {
10596
+ const trimmed = value.trim();
10597
+ return trimmed.length > 0 ? trimmed : void 0;
10598
+ }
10599
+ function normalizeTableSelection(value) {
10600
+ if (typeof value === "string") {
10601
+ return Array.from(
10602
+ new Set(
10603
+ value.split(",").map(normalizeTableSelector).filter((entry) => Boolean(entry))
10604
+ )
10605
+ );
10606
+ }
10607
+ if (Array.isArray(value)) {
10608
+ return Array.from(
10609
+ new Set(
10610
+ value.map((entry) => typeof entry === "string" ? normalizeTableSelector(entry) : void 0).filter((entry) => Boolean(entry))
10611
+ )
10612
+ );
10613
+ }
10614
+ return [];
10615
+ }
10616
+ function matchesTableSelector(schemaName, tableName, selector) {
10617
+ const separatorIndex = selector.indexOf(".");
10618
+ if (separatorIndex < 0) {
10619
+ return tableName === selector;
10620
+ }
10621
+ const selectorSchema = selector.slice(0, separatorIndex).trim();
10622
+ const selectorTable = selector.slice(separatorIndex + 1).trim();
10623
+ return selectorSchema === schemaName && selectorTable === tableName;
10624
+ }
10625
+ function shouldKeepTable(schemaName, tableName, filter) {
10626
+ const included = filter.includeTables.length === 0 || filter.includeTables.some((selector) => matchesTableSelector(schemaName, tableName, selector));
10627
+ if (!included) {
10628
+ return false;
10629
+ }
10630
+ return !filter.excludeTables.some((selector) => matchesTableSelector(schemaName, tableName, selector));
10631
+ }
10632
+ function hasTableFilters(filter) {
10633
+ return filter.includeTables.length > 0 || filter.excludeTables.length > 0;
10634
+ }
10635
+ function filterIntrospectionSnapshot(snapshot, filter) {
10636
+ if (!hasTableFilters(filter)) {
10637
+ return snapshot;
10638
+ }
10639
+ const schemas = {};
10640
+ for (const [schemaName, schema] of Object.entries(snapshot.schemas)) {
10641
+ const tables = Object.fromEntries(
10642
+ Object.entries(schema.tables).filter(([tableName]) => shouldKeepTable(schemaName, tableName, filter))
10643
+ );
10644
+ if (Object.keys(tables).length === 0) {
10645
+ continue;
10646
+ }
10647
+ schemas[schemaName] = {
10648
+ ...schema,
10649
+ tables
10650
+ };
10651
+ }
10652
+ if (Object.keys(schemas).length === 0) {
10653
+ const includeLabel = filter.includeTables.length > 0 ? ` includeTables=${filter.includeTables.join(", ")}` : "";
10654
+ const excludeLabel = filter.excludeTables.length > 0 ? ` excludeTables=${filter.excludeTables.join(", ")}` : "";
10655
+ throw new Error(
10656
+ `Generator table filters matched no tables after schema selection.${includeLabel}${excludeLabel}`
10657
+ );
10658
+ }
10659
+ return {
10660
+ ...snapshot,
10661
+ schemas
10662
+ };
10663
+ }
10664
+
9307
10665
  // src/generator/config.ts
9308
10666
  var POSTGRES_PROTOCOLS = /* @__PURE__ */ new Set(["postgres:", "postgresql:"]);
9309
10667
  var DEFAULT_CONFIG_CANDIDATES = [
@@ -9314,13 +10672,20 @@ var DEFAULT_CONFIG_CANDIDATES = [
9314
10672
  ".athena.config.ts",
9315
10673
  ".athena.config.js"
9316
10674
  ];
9317
- var DEFAULT_TARGETS = {
10675
+ var LEGACY_DEFAULT_TARGETS = {
9318
10676
  model: "athena/models/{schema_kebab}/{model_kebab}.ts",
9319
10677
  schema: "athena/schemas/{schema_kebab}.ts",
9320
10678
  database: "athena/relations.ts",
9321
10679
  registry: "athena/config.ts"
9322
10680
  };
9323
- var DEFAULT_OUTPUT_FORMAT = "define-model";
10681
+ var ATHENA_DIRECT_TARGETS = {
10682
+ model: "athena/models/{schema_kebab}/{model_kebab}.ts",
10683
+ schema: "athena/schemas/{schema_kebab}.ts",
10684
+ database: "athena/relations.ts",
10685
+ registry: "athena/registry.generated.ts"
10686
+ };
10687
+ var DEFAULT_OUTPUT_FORMAT = "table-builder";
10688
+ var DEFAULT_OUTPUT_PRESET = "athena-direct";
9324
10689
  var DEFAULT_NAMING = {
9325
10690
  modelType: "pascal",
9326
10691
  modelConst: "camel",
@@ -9339,6 +10704,10 @@ var DEFAULT_EXPERIMENTAL_FLAGS = {
9339
10704
  var DEFAULT_INTERNAL_CONFIG = {
9340
10705
  schemaVersion: 1
9341
10706
  };
10707
+ var DEFAULT_FILTER_CONFIG = {
10708
+ includeTables: [],
10709
+ excludeTables: []
10710
+ };
9342
10711
  var PROJECT_ENV_FILENAMES = [".env", ".env.local"];
9343
10712
  var DIRECT_CONNECTION_STRING_ENV_KEYS = [
9344
10713
  "ATHENA_GENERATOR_PG_URL",
@@ -9357,10 +10726,13 @@ var GATEWAY_API_KEY_ENV_KEYS = [
9357
10726
  ];
9358
10727
  var GENERATOR_SCHEMA_ENV_KEYS = ["ATHENA_GENERATOR_SCHEMAS"];
9359
10728
  var OUTPUT_FORMAT_ENV_KEYS = ["ATHENA_GENERATOR_OUTPUT_FORMAT"];
10729
+ var OUTPUT_PRESET_ENV_KEYS = ["ATHENA_GENERATOR_OUTPUT_PRESET"];
9360
10730
  var MODEL_TARGET_ENV_KEYS = ["ATHENA_GENERATOR_MODEL_TARGET"];
9361
10731
  var SCHEMA_TARGET_ENV_KEYS = ["ATHENA_GENERATOR_SCHEMA_TARGET"];
9362
10732
  var DATABASE_TARGET_ENV_KEYS = ["ATHENA_GENERATOR_DATABASE_TARGET"];
9363
10733
  var REGISTRY_TARGET_ENV_KEYS = ["ATHENA_GENERATOR_REGISTRY_TARGET"];
10734
+ var TABLES_ENV_KEYS = ["ATHENA_GENERATOR_TABLES"];
10735
+ var EXCLUDE_TABLES_ENV_KEYS = ["ATHENA_GENERATOR_EXCLUDE_TABLES"];
9364
10736
  var PLACEHOLDER_MAP_ENV_KEYS = ["ATHENA_GENERATOR_PLACEHOLDER_MAP"];
9365
10737
  var MODEL_TYPE_ENV_KEYS = ["ATHENA_GENERATOR_MODEL_TYPE", "ATHENA_GENERATOR_MODEL_STYLE"];
9366
10738
  var MODEL_CONST_ENV_KEYS = ["ATHENA_GENERATOR_MODEL_CONST"];
@@ -9375,7 +10747,12 @@ var SCYLLA_PROVIDER_CONTRACTS_ENV_KEYS = ["ATHENA_GENERATOR_SCYLLA_PROVIDER_CONT
9375
10747
  var ENV_ONLY_CONFIG_PATH = "[environment defaults]";
9376
10748
  var NAMING_STYLE_VALUES = ["preserve", "camel", "pascal", "snake", "kebab"];
9377
10749
  var OUTPUT_FORMAT_VALUES = ["define-model", "table-builder"];
10750
+ var OUTPUT_PRESET_VALUES = ["legacy", "athena-direct"];
9378
10751
  var BACKEND_TYPE_VALUES = ["athena", "postgrest", "postgresql", "scylladb"];
10752
+ var OUTPUT_PRESET_TARGETS = {
10753
+ legacy: LEGACY_DEFAULT_TARGETS,
10754
+ "athena-direct": ATHENA_DIRECT_TARGETS
10755
+ };
9379
10756
  function normalizeRawEnvValue(rawValue) {
9380
10757
  if (rawValue.startsWith('"') && rawValue.endsWith('"') && rawValue.length >= 2) {
9381
10758
  const inner = rawValue.slice(1, -1);
@@ -9511,7 +10888,7 @@ function deriveDatabaseNameFromConnectionString(connectionString) {
9511
10888
  return void 0;
9512
10889
  }
9513
10890
  }
9514
- function normalizeOptionalString(value, fallbackKeys) {
10891
+ function normalizeOptionalString3(value, fallbackKeys) {
9515
10892
  if (typeof value === "string") {
9516
10893
  const trimmed = value.trim();
9517
10894
  if (trimmed.length > 0) {
@@ -9521,7 +10898,7 @@ function normalizeOptionalString(value, fallbackKeys) {
9521
10898
  return resolveFallbackValue(fallbackKeys);
9522
10899
  }
9523
10900
  function normalizeRequiredString(value, fieldLabel, fallbackKeys) {
9524
- const resolved = normalizeOptionalString(value, fallbackKeys);
10901
+ const resolved = normalizeOptionalString3(value, fallbackKeys);
9525
10902
  if (resolved) {
9526
10903
  return resolved;
9527
10904
  }
@@ -9582,11 +10959,19 @@ function normalizeExperimentalFlags(input) {
9582
10959
  )
9583
10960
  };
9584
10961
  }
10962
+ function normalizeFilterConfig(input) {
10963
+ return {
10964
+ includeTables: normalizeTableSelection(input?.includeTables),
10965
+ excludeTables: normalizeTableSelection(input?.excludeTables)
10966
+ };
10967
+ }
9585
10968
  function normalizeOutputConfig(output) {
10969
+ const preset = output?.preset ?? DEFAULT_OUTPUT_PRESET;
9586
10970
  return {
9587
10971
  format: output?.format ?? DEFAULT_OUTPUT_FORMAT,
10972
+ preset,
9588
10973
  targets: {
9589
- ...DEFAULT_TARGETS,
10974
+ ...OUTPUT_PRESET_TARGETS[preset],
9590
10975
  ...output?.targets ?? {}
9591
10976
  },
9592
10977
  placeholderMap: {
@@ -9601,7 +10986,7 @@ function normalizeProviderConfig(provider) {
9601
10986
  "provider.connectionString",
9602
10987
  DIRECT_CONNECTION_STRING_ENV_KEYS
9603
10988
  );
9604
- const database = normalizeOptionalString(provider.database, POSTGRES_DATABASE_ENV_KEYS) ?? deriveDatabaseNameFromConnectionString(connectionString);
10989
+ const database = normalizeOptionalString3(provider.database, POSTGRES_DATABASE_ENV_KEYS) ?? deriveDatabaseNameFromConnectionString(connectionString);
9605
10990
  return {
9606
10991
  ...provider,
9607
10992
  connectionString: applyPostgresPasswordFallback(connectionString),
@@ -9620,7 +11005,7 @@ function normalizeProviderConfig(provider) {
9620
11005
  "provider.apiKey",
9621
11006
  GATEWAY_API_KEY_ENV_KEYS
9622
11007
  );
9623
- const database = normalizeOptionalString(provider.database, POSTGRES_DATABASE_ENV_KEYS) ?? "postgres";
11008
+ const database = normalizeOptionalString3(provider.database, POSTGRES_DATABASE_ENV_KEYS) ?? "postgres";
9624
11009
  return {
9625
11010
  ...provider,
9626
11011
  gatewayUrl,
@@ -9635,7 +11020,7 @@ function normalizeProviderConfig(provider) {
9635
11020
  "Generator config is missing provider.contactPoints for scylla direct mode."
9636
11021
  );
9637
11022
  }
9638
- const keyspace = normalizeOptionalString(provider.keyspace, []);
11023
+ const keyspace = normalizeOptionalString3(provider.keyspace, []);
9639
11024
  if (!keyspace) {
9640
11025
  throw new Error(
9641
11026
  "Generator config is missing provider.keyspace for scylla direct mode."
@@ -9646,7 +11031,7 @@ function normalizeProviderConfig(provider) {
9646
11031
  mode: "direct",
9647
11032
  contactPoints: provider.contactPoints.slice(),
9648
11033
  keyspace,
9649
- datacenter: normalizeOptionalString(provider.datacenter, [])
11034
+ datacenter: normalizeOptionalString3(provider.datacenter, [])
9650
11035
  };
9651
11036
  }
9652
11037
  return provider;
@@ -9666,6 +11051,10 @@ function normalizeGeneratorConfig(input) {
9666
11051
  ...DEFAULT_NAMING,
9667
11052
  ...input.naming ?? {}
9668
11053
  },
11054
+ filter: {
11055
+ ...DEFAULT_FILTER_CONFIG,
11056
+ ...normalizeFilterConfig(input.filter)
11057
+ },
9669
11058
  features: normalizeFeatureFlags(input.features),
9670
11059
  experimental: normalizeExperimentalFlags(input.experimental),
9671
11060
  internal: {
@@ -9729,16 +11118,18 @@ function importConfigModule(moduleSpecifier) {
9729
11118
  }
9730
11119
  function buildEnvironmentOutputConfig() {
9731
11120
  const format = resolveOptionalOneOf(OUTPUT_FORMAT_ENV_KEYS, OUTPUT_FORMAT_VALUES);
11121
+ const preset = resolveOptionalOneOf(OUTPUT_PRESET_ENV_KEYS, OUTPUT_PRESET_VALUES);
9732
11122
  const modelTarget = resolveFallbackValue(MODEL_TARGET_ENV_KEYS);
9733
11123
  const schemaTarget = resolveFallbackValue(SCHEMA_TARGET_ENV_KEYS);
9734
11124
  const databaseTarget = resolveFallbackValue(DATABASE_TARGET_ENV_KEYS);
9735
11125
  const registryTarget = resolveFallbackValue(REGISTRY_TARGET_ENV_KEYS);
9736
11126
  const placeholderMap = resolveOptionalJson(PLACEHOLDER_MAP_ENV_KEYS);
9737
- if (format === void 0 && modelTarget === void 0 && schemaTarget === void 0 && databaseTarget === void 0 && registryTarget === void 0 && placeholderMap === void 0) {
11127
+ if (format === void 0 && preset === void 0 && modelTarget === void 0 && schemaTarget === void 0 && databaseTarget === void 0 && registryTarget === void 0 && placeholderMap === void 0) {
9738
11128
  return void 0;
9739
11129
  }
9740
11130
  return {
9741
11131
  format,
11132
+ preset,
9742
11133
  targets: {
9743
11134
  ...modelTarget ? { model: modelTarget } : {},
9744
11135
  ...schemaTarget ? { schema: schemaTarget } : {},
@@ -9748,6 +11139,17 @@ function buildEnvironmentOutputConfig() {
9748
11139
  placeholderMap
9749
11140
  };
9750
11141
  }
11142
+ function buildEnvironmentFilterConfig() {
11143
+ const includeTables = resolveFallbackValue(TABLES_ENV_KEYS);
11144
+ const excludeTables = resolveFallbackValue(EXCLUDE_TABLES_ENV_KEYS);
11145
+ if (includeTables === void 0 && excludeTables === void 0) {
11146
+ return void 0;
11147
+ }
11148
+ return {
11149
+ ...includeTables !== void 0 ? { includeTables } : {},
11150
+ ...excludeTables !== void 0 ? { excludeTables } : {}
11151
+ };
11152
+ }
9751
11153
  function buildEnvironmentNamingConfig() {
9752
11154
  const modelType = resolveOptionalOneOf(MODEL_TYPE_ENV_KEYS, NAMING_STYLE_VALUES);
9753
11155
  const modelConst = resolveOptionalOneOf(MODEL_CONST_ENV_KEYS, NAMING_STYLE_VALUES);
@@ -9794,7 +11196,7 @@ function buildEnvironmentProviderConfig() {
9794
11196
  kind: "postgres",
9795
11197
  mode: "direct",
9796
11198
  connectionString: directConnectionString,
9797
- database: normalizeOptionalString(void 0, POSTGRES_DATABASE_ENV_KEYS),
11199
+ database: normalizeOptionalString3(void 0, POSTGRES_DATABASE_ENV_KEYS),
9798
11200
  schemas: normalizeSchemaSelection(resolveFallbackValue(GENERATOR_SCHEMA_ENV_KEYS))
9799
11201
  };
9800
11202
  }
@@ -9807,7 +11209,7 @@ function buildEnvironmentProviderConfig() {
9807
11209
  mode: "gateway",
9808
11210
  gatewayUrl,
9809
11211
  apiKey,
9810
- database: normalizeOptionalString(void 0, POSTGRES_DATABASE_ENV_KEYS),
11212
+ database: normalizeOptionalString3(void 0, POSTGRES_DATABASE_ENV_KEYS),
9811
11213
  schemas: normalizeSchemaSelection(resolveFallbackValue(GENERATOR_SCHEMA_ENV_KEYS)),
9812
11214
  backend
9813
11215
  };
@@ -9823,6 +11225,7 @@ function createEnvironmentGeneratorConfig() {
9823
11225
  provider,
9824
11226
  output: buildEnvironmentOutputConfig(),
9825
11227
  naming: buildEnvironmentNamingConfig(),
11228
+ filter: buildEnvironmentFilterConfig(),
9826
11229
  features: buildEnvironmentFeatureFlags(),
9827
11230
  experimental: buildEnvironmentExperimentalFlags()
9828
11231
  };
@@ -10308,7 +11711,7 @@ ${schemaEntries}
10308
11711
  content
10309
11712
  };
10310
11713
  }
10311
- function renderRegistryArtifact(registryPath, databasePath, databaseConstName, registryConstName, databaseName, generatedAt, outputFormat, schemaVersion) {
11714
+ function renderRegistryArtifact(registryPath, databasePath, databaseConstName, registryConstName, databaseName, generatedAt, outputPreset, outputFormat, schemaVersion) {
10312
11715
  const databaseImportPath = toModuleImportPath(registryPath, databasePath);
10313
11716
  const content = `import { defineRegistry } from '@xylex-group/athena'
10314
11717
  import { ${databaseConstName} } from '${databaseImportPath}'
@@ -10317,6 +11720,7 @@ export const __athena_schema_meta = {
10317
11720
  schemaVersion: ${schemaVersion},
10318
11721
  generatedAt: ${escapeStringLiteral(generatedAt)},
10319
11722
  database: ${escapeStringLiteral(databaseName)},
11723
+ outputPreset: ${escapeStringLiteral(outputPreset)},
10320
11724
  outputFormat: ${escapeStringLiteral(outputFormat)},
10321
11725
  } as const
10322
11726
 
@@ -10486,6 +11890,7 @@ function composeGeneratorArtifacts(input) {
10486
11890
  toSafeIdentifier("registry", config.naming.registryConst, "registry"),
10487
11891
  databaseName,
10488
11892
  snapshot.generatedAt,
11893
+ config.output.preset,
10489
11894
  config.output.format,
10490
11895
  config.internal.schemaVersion
10491
11896
  )
@@ -10591,7 +11996,7 @@ export const ${descriptor.tableConstName} = table(${escapeStringLiteral(descript
10591
11996
  .columns({
10592
11997
  ${columnLines}
10593
11998
  })
10594
- .primaryKey(${descriptor.table.primaryKey.map((value) => escapeStringLiteral(value)).join(", ")})
11999
+ ${descriptor.table.primaryKey.length > 0 ? `.primaryKey(${descriptor.table.primaryKey.map((value) => escapeStringLiteral(value)).join(", ")})` : ".withoutPrimaryKey()"}
10595
12000
  ${relationsAssignment ? `${relationsAssignment}` : ""}
10596
12001
  export type ${descriptor.rowTypeName} = RowOf<typeof ${descriptor.tableConstName}>
10597
12002
  export type ${descriptor.insertTypeName} = InsertOf<typeof ${descriptor.tableConstName}>
@@ -10688,11 +12093,12 @@ ${nullableLines}
10688
12093
  }
10689
12094
  function generateArtifactsFromSnapshot(snapshot, config) {
10690
12095
  const normalizedConfig = "internal" in config ? config : normalizeGeneratorConfig(config);
12096
+ const filteredSnapshot = filterIntrospectionSnapshot(snapshot, normalizedConfig.filter);
10691
12097
  if (normalizedConfig.output.format === "table-builder") {
10692
- return generateTableBuilderArtifactsFromSnapshot(snapshot, normalizedConfig);
12098
+ return generateTableBuilderArtifactsFromSnapshot(filteredSnapshot, normalizedConfig);
10693
12099
  }
10694
12100
  return composeGeneratorArtifacts({
10695
- snapshot,
12101
+ snapshot: filteredSnapshot,
10696
12102
  config: normalizedConfig,
10697
12103
  createModelDescriptor({ providerName, databaseName, schemaName, tableName, table: table2 }) {
10698
12104
  const modelConstName = toSafeIdentifier(
@@ -10722,7 +12128,7 @@ function generateArtifactsFromSnapshot(snapshot, config) {
10722
12128
  table: table2
10723
12129
  };
10724
12130
  },
10725
- renderModelArtifact: (descriptor) => renderModelArtifact2(snapshot.database, descriptor, normalizedConfig)
12131
+ renderModelArtifact: (descriptor) => renderModelArtifact2(filteredSnapshot.database, descriptor, normalizedConfig)
10726
12132
  });
10727
12133
  }
10728
12134
 
@@ -10842,16 +12248,25 @@ async function fileExists(path) {
10842
12248
  }
10843
12249
  async function writeArtifacts(files, cwd) {
10844
12250
  const writtenFiles = [];
12251
+ const skippedFiles = [];
10845
12252
  for (const file of files) {
10846
12253
  const absolutePath = resolve(cwd, file.path);
10847
12254
  if (!canOverwriteArtifact(file) && await fileExists(absolutePath)) {
12255
+ skippedFiles.push({
12256
+ kind: file.kind,
12257
+ path: file.path,
12258
+ reason: "protected-existing-file"
12259
+ });
10848
12260
  continue;
10849
12261
  }
10850
12262
  await mkdir(dirname(absolutePath), { recursive: true });
10851
12263
  await writeFile(absolutePath, file.content, "utf8");
10852
12264
  writtenFiles.push(file.path);
10853
12265
  }
10854
- return writtenFiles;
12266
+ return {
12267
+ writtenFiles,
12268
+ skippedFiles
12269
+ };
10855
12270
  }
10856
12271
  async function runSchemaGenerator(options = {}) {
10857
12272
  const cwd = options.cwd ?? process.cwd();
@@ -10865,12 +12280,13 @@ async function runSchemaGenerator(options = {}) {
10865
12280
  schemas: resolveProviderSchemas(config.provider)
10866
12281
  });
10867
12282
  const generated = generateArtifactsFromSnapshot(snapshot, config);
10868
- const writtenFiles = options.dryRun ? [] : await writeArtifacts(generated.files, cwd);
12283
+ const writeResult = options.dryRun ? { writtenFiles: [], skippedFiles: [] } : await writeArtifacts(generated.files, cwd);
10869
12284
  return {
10870
12285
  ...generated,
10871
12286
  configPath,
10872
12287
  config,
10873
- writtenFiles
12288
+ writtenFiles: writeResult.writtenFiles,
12289
+ skippedFiles: writeResult.skippedFiles
10874
12290
  };
10875
12291
  }
10876
12292
 
@@ -10939,15 +12355,15 @@ function readCookieFromHeaders(headers, name) {
10939
12355
  }
10940
12356
  return parseCookies(cookieHeader).get(name);
10941
12357
  }
10942
- function isRecord11(value) {
12358
+ function isRecord12(value) {
10943
12359
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
10944
12360
  }
10945
12361
  function resolveSessionCandidate(value) {
10946
- if (!isRecord11(value)) {
12362
+ if (!isRecord12(value)) {
10947
12363
  return null;
10948
12364
  }
10949
- const session = isRecord11(value.session) ? value.session : void 0;
10950
- const user = isRecord11(value.user) ? value.user : void 0;
12365
+ const session = isRecord12(value.session) ? value.session : void 0;
12366
+ const user = isRecord12(value.user) ? value.user : void 0;
10951
12367
  if (session && typeof session.token === "string" && session.token.length > 0 && user) {
10952
12368
  return {
10953
12369
  session,
@@ -10957,7 +12373,7 @@ function resolveSessionCandidate(value) {
10957
12373
  return null;
10958
12374
  }
10959
12375
  function inferSessionPair(returned) {
10960
- return resolveSessionCandidate(returned) ?? (isRecord11(returned) ? resolveSessionCandidate(returned.data) : null) ?? (isRecord11(returned) ? resolveSessionCandidate(returned.session) : null);
12376
+ return resolveSessionCandidate(returned) ?? (isRecord12(returned) ? resolveSessionCandidate(returned.data) : null) ?? (isRecord12(returned) ? resolveSessionCandidate(returned.session) : null);
10961
12377
  }
10962
12378
  function resolveResponseHeaders(ctx) {
10963
12379
  if (ctx.context.responseHeaders instanceof Headers) {
@@ -10980,23 +12396,23 @@ function normalizeBasePath(basePath) {
10980
12396
  function isDynamicBaseURLConfig2(baseURL) {
10981
12397
  return typeof baseURL === "object" && baseURL !== null && "allowedHosts" in baseURL && Array.isArray(baseURL.allowedHosts);
10982
12398
  }
10983
- function getRequestUrl(request) {
12399
+ function getRequestUrl(request2) {
10984
12400
  try {
10985
- return new URL(request.url);
12401
+ return new URL(request2.url);
10986
12402
  } catch {
10987
12403
  return new URL("http://localhost");
10988
12404
  }
10989
12405
  }
10990
- function getRequestHost(request, url) {
10991
- const forwardedHost = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim();
10992
- const host = forwardedHost || request.headers.get("host") || url.host;
12406
+ function getRequestHost(request2, url) {
12407
+ const forwardedHost = request2.headers.get("x-forwarded-host")?.split(",")[0]?.trim();
12408
+ const host = forwardedHost || request2.headers.get("host") || url.host;
10993
12409
  return host || null;
10994
12410
  }
10995
- function getRequestProtocol(request, configuredProtocol, url) {
12411
+ function getRequestProtocol(request2, configuredProtocol, url) {
10996
12412
  if (configuredProtocol === "http" || configuredProtocol === "https") {
10997
12413
  return configuredProtocol;
10998
12414
  }
10999
- const forwardedProto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
12415
+ const forwardedProto = request2.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
11000
12416
  if (forwardedProto === "http" || forwardedProto === "https") {
11001
12417
  return forwardedProto;
11002
12418
  }
@@ -11005,12 +12421,12 @@ function getRequestProtocol(request, configuredProtocol, url) {
11005
12421
  }
11006
12422
  return "http";
11007
12423
  }
11008
- function resolveRequestBaseURL(baseURL, request) {
12424
+ function resolveRequestBaseURL(baseURL, request2) {
11009
12425
  if (typeof baseURL === "string") {
11010
12426
  return normalizeBaseURL(baseURL);
11011
12427
  }
11012
- const requestUrl = getRequestUrl(request);
11013
- const host = getRequestHost(request, requestUrl);
12428
+ const requestUrl = getRequestUrl(request2);
12429
+ const host = getRequestHost(request2, requestUrl);
11014
12430
  if (!host) {
11015
12431
  return null;
11016
12432
  }
@@ -11020,7 +12436,7 @@ function resolveRequestBaseURL(baseURL, request) {
11020
12436
  return null;
11021
12437
  }
11022
12438
  }
11023
- const protocol = typeof baseURL === "object" && baseURL !== null ? getRequestProtocol(request, baseURL.protocol, requestUrl) : getRequestProtocol(request, void 0, requestUrl);
12439
+ const protocol = typeof baseURL === "object" && baseURL !== null ? getRequestProtocol(request2, baseURL.protocol, requestUrl) : getRequestProtocol(request2, void 0, requestUrl);
11024
12440
  return `${protocol}://${host}`;
11025
12441
  }
11026
12442
  function getOrigin(baseURL) {
@@ -11033,16 +12449,16 @@ function getOrigin(baseURL) {
11033
12449
  return void 0;
11034
12450
  }
11035
12451
  }
11036
- async function resolveTrustedOrigins(config, baseURL, request) {
11037
- const resolved = typeof config.trustedOrigins === "function" ? await config.trustedOrigins(request) : config.trustedOrigins ?? [];
12452
+ async function resolveTrustedOrigins(config, baseURL, request2) {
12453
+ const resolved = typeof config.trustedOrigins === "function" ? await config.trustedOrigins(request2) : config.trustedOrigins ?? [];
11038
12454
  const values = [
11039
12455
  getOrigin(baseURL),
11040
12456
  ...resolved
11041
12457
  ];
11042
12458
  return Array.from(new Set(values.filter((value) => typeof value === "string" && value.length > 0)));
11043
12459
  }
11044
- async function resolveTrustedProviders(config, request) {
11045
- const configured = typeof config.trustedProviders === "function" ? await config.trustedProviders(request) : config.trustedProviders ?? [];
12460
+ async function resolveTrustedProviders(config, request2) {
12461
+ const configured = typeof config.trustedProviders === "function" ? await config.trustedProviders(request2) : config.trustedProviders ?? [];
11046
12462
  const values = [
11047
12463
  ...Object.keys(config.socialProviders ?? {}),
11048
12464
  ...configured
@@ -11167,9 +12583,9 @@ function athenaAuth(config) {
11167
12583
  }
11168
12584
  return ctx;
11169
12585
  };
11170
- const resolveRequestContext = async (request) => {
11171
- const requestUrl = getRequestUrl(request);
11172
- const resolvedBaseURL = resolveRequestBaseURL(config.baseURL, request);
12586
+ const resolveRequestContext = async (request2) => {
12587
+ const requestUrl = getRequestUrl(request2);
12588
+ const resolvedBaseURL = resolveRequestBaseURL(config.baseURL, request2);
11173
12589
  if (!resolvedBaseURL) {
11174
12590
  throw new Error(
11175
12591
  isDynamicBaseURLConfig2(config.baseURL) ? "Could not resolve base URL from request. Check allowedHosts/baseURL." : "Could not resolve base URL from request."
@@ -11180,17 +12596,17 @@ function athenaAuth(config) {
11180
12596
  session: config.session,
11181
12597
  advanced: config.advanced
11182
12598
  });
11183
- const trustedOrigins = await resolveTrustedOrigins(config, resolvedBaseURL, request);
11184
- const trustedProviders = await resolveTrustedProviders(config, request);
12599
+ const trustedOrigins = await resolveTrustedOrigins(config, resolvedBaseURL, request2);
12600
+ const trustedProviders = await resolveTrustedProviders(config, request2);
11185
12601
  return {
11186
12602
  auth,
11187
- request,
12603
+ request: request2,
11188
12604
  url: requestUrl,
11189
12605
  path: requestUrl.pathname,
11190
12606
  basePath: normalizedBasePath,
11191
12607
  baseURL: resolvedBaseURL,
11192
12608
  origin: getOrigin(resolvedBaseURL) ?? resolvedBaseURL,
11193
- headers: request.headers,
12609
+ headers: request2.headers,
11194
12610
  cookies: requestCookies,
11195
12611
  trustedOrigins,
11196
12612
  trustedProviders,
@@ -11203,8 +12619,8 @@ function athenaAuth(config) {
11203
12619
  socialProviders: auth.socialProviders
11204
12620
  };
11205
12621
  };
11206
- const handler = async (request) => {
11207
- const requestContext = await resolveRequestContext(request);
12622
+ const handler = async (request2) => {
12623
+ const requestContext = await resolveRequestContext(request2);
11208
12624
  if (typeof config.handler !== "function") {
11209
12625
  return createJsonResponse(
11210
12626
  {
@@ -11225,7 +12641,7 @@ function athenaAuth(config) {
11225
12641
  const responseHeaders = new Headers(response.headers);
11226
12642
  await runAfterHooks({
11227
12643
  path: requestContext.path,
11228
- headers: request.headers,
12644
+ headers: request2.headers,
11229
12645
  context: {
11230
12646
  responseHeaders,
11231
12647
  returned: result.returned,
@@ -11301,6 +12717,6 @@ function athenaAuth(config) {
11301
12717
  return auth;
11302
12718
  }
11303
12719
 
11304
- export { ATHENA_AUTH_BASE_ERROR_CODES, AthenaClient, AthenaError, AthenaErrorCategory, AthenaErrorCode, AthenaErrorKind, AthenaGatewayError, AthenaStorageError, AthenaStorageErrorCode, Backend, DEFAULT_POSTGRES_SCHEMAS, assertInt, athenaAuth, boolean, coerceInt, createAthenaStorageError, createAuthClient, createAuthReactEmailInput, createClient, createModelFormAdapter, createPostgresIntrospectionProvider, createTypedClient, defineAthenaAuthConfig, defineAuthEmailTemplate, defineDatabase, defineGeneratorConfig, defineModel, defineRegistry, defineSchema, enumeration, findGeneratorConfigPath, generateArtifactsFromSnapshot, generatorEnv, getAthenaDebugAst, identifier, isAthenaGatewayError, isOk, json, loadGeneratorConfig, normalizeAthenaError, normalizeAthenaGatewayBaseUrl, normalizeGeneratorConfig, normalizeSchemaSelection, number, parseBooleanFlag2 as parseBooleanFlag, renderAthenaReactEmail, requireAffected, requireSuccess, resolveGeneratorProvider, resolvePostgresColumnType, resolveProviderSchemas, runSchemaGenerator, storageSdkManifest, string, table, toModelFormDefaults, toModelPayload, unwrap, unwrapOne, unwrapRows, verifyAthenaGatewayUrl, withRetry };
12720
+ export { ATHENA_AUTH_ADMIN_LIMITS, ATHENA_AUTH_BASE_ERROR_CODES, ATHENA_AUTH_MAX_ADMIN_JSON_BYTES, ATHENA_AUTH_MAX_ADMIN_JSON_DEPTH, ATHENA_AUTH_MAX_TEMPLATE_VARIABLES, ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH, AthenaChatError, AthenaClient, AthenaError, AthenaErrorCategory, AthenaErrorCode, AthenaErrorKind, AthenaGatewayError, AthenaStorageError, AthenaStorageErrorCode, Backend, DEFAULT_POSTGRES_SCHEMAS, assertInt, athenaAuth, boolean, chatSdkManifest, coerceInt, createAthenaStorageError, createAuthClient, createAuthReactEmailInput, createClient, createModelFormAdapter, createPostgresIntrospectionProvider, createTypedClient, defineAthenaAuthConfig, defineAuthEmailTemplate, defineDatabase, defineGeneratorConfig, defineModel, defineRegistry, defineSchema, enumeration, filterIntrospectionSnapshot, findGeneratorConfigPath, generateArtifactsFromSnapshot, generatorEnv, getAthenaDebugAst, identifier, isAthenaGatewayError, isOk, json, loadGeneratorConfig, normalizeAthenaError, normalizeAthenaGatewayBaseUrl, normalizeGeneratorConfig, normalizeSchemaSelection, normalizeTableSelection, number, parseBooleanFlag2 as parseBooleanFlag, renderAthenaReactEmail, requireAffected, requireSuccess, resolveGeneratorProvider, resolvePostgresColumnType, resolveProviderSchemas, runSchemaGenerator, storageSdkManifest, string, table, toModelFormDefaults, toModelPayload, unwrap, unwrapChatMessage, unwrapChatRoom, unwrapOne, unwrapRows, verifyAthenaGatewayUrl, withRetry };
11305
12721
  //# sourceMappingURL=index.js.map
11306
12722
  //# sourceMappingURL=index.js.map