@xylex-group/athena 2.4.0 → 2.6.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 (47) hide show
  1. package/README.md +124 -2
  2. package/bin/athena-js.js +0 -0
  3. package/dist/browser.cjs +2245 -151
  4. package/dist/browser.cjs.map +1 -1
  5. package/dist/browser.d.cts +8 -7
  6. package/dist/browser.d.ts +8 -7
  7. package/dist/browser.js +2238 -152
  8. package/dist/browser.js.map +1 -1
  9. package/dist/cli/index.cjs +1073 -102
  10. package/dist/cli/index.cjs.map +1 -1
  11. package/dist/cli/index.d.cts +3 -3
  12. package/dist/cli/index.d.ts +3 -3
  13. package/dist/cli/index.js +1073 -102
  14. package/dist/cli/index.js.map +1 -1
  15. package/dist/cookies.d.cts +1 -174
  16. package/dist/cookies.d.ts +1 -174
  17. package/dist/index-CVcQCGyG.d.cts +174 -0
  18. package/dist/index-CVcQCGyG.d.ts +174 -0
  19. package/dist/index.cjs +2246 -152
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +8 -7
  22. package/dist/index.d.ts +8 -7
  23. package/dist/index.js +2239 -153
  24. package/dist/index.js.map +1 -1
  25. package/dist/{model-form-GzTqhEzM.d.cts → model-form-BaHWi3gm.d.cts} +9 -5
  26. package/dist/{model-form-C0FAbOaf.d.ts → model-form-Dh6gWjL0.d.ts} +9 -5
  27. package/dist/{pipeline-CR4V15jF.d.ts → pipeline-Ce3pTw5h.d.ts} +1 -1
  28. package/dist/{pipeline-DZeExYMA.d.cts → pipeline-D1ZYeoH7.d.cts} +1 -1
  29. package/dist/{react-email-CQJq92zQ.d.cts → react-email-B8O1Jeff.d.cts} +637 -30
  30. package/dist/{react-email-BuApZuyG.d.ts → react-email-CDEF0jij.d.ts} +637 -30
  31. package/dist/react.cjs +84 -4
  32. package/dist/react.cjs.map +1 -1
  33. package/dist/react.d.cts +4 -4
  34. package/dist/react.d.ts +4 -4
  35. package/dist/react.js +84 -4
  36. package/dist/react.js.map +1 -1
  37. package/dist/{types-D1JvL21V.d.cts → types-CUuo4NDi.d.cts} +1 -1
  38. package/dist/{types-09Q4D86N.d.cts → types-DSX6AT5B.d.cts} +3 -3
  39. package/dist/{types-09Q4D86N.d.ts → types-DSX6AT5B.d.ts} +3 -3
  40. package/dist/{types-DU3gNdFv.d.ts → types-DapchQY5.d.ts} +1 -1
  41. package/dist/utils.cjs +131 -0
  42. package/dist/utils.cjs.map +1 -1
  43. package/dist/utils.d.cts +42 -1
  44. package/dist/utils.d.ts +42 -1
  45. package/dist/utils.js +117 -1
  46. package/dist/utils.js.map +1 -1
  47. package/package.json +193 -192
@@ -663,6 +663,54 @@ function normalizeAthenaError(resultOrError, context) {
663
663
  raw: resultOrError
664
664
  };
665
665
  }
666
+ function defaultShouldRetry(error) {
667
+ const normalized = normalizeAthenaError(error);
668
+ return normalized.kind === "transient" || normalized.kind === "rate_limit";
669
+ }
670
+ function computeDelayMs(attempt, error, config) {
671
+ const baseDelay = config.baseDelayMs;
672
+ const rawDelay = typeof config.backoff === "function" ? config.backoff(attempt, error) : config.backoff === "linear" ? baseDelay * attempt : baseDelay * Math.pow(2, attempt - 1);
673
+ const safeDelay = Number.isFinite(rawDelay) ? Math.max(0, rawDelay) : 0;
674
+ const clamped = Math.min(config.maxDelayMs, safeDelay);
675
+ const jitterFactor = typeof config.jitter === "number" ? Math.max(0, Math.min(1, config.jitter)) : config.jitter ? 0.2 : 0;
676
+ if (!jitterFactor) return clamped;
677
+ const deviation = clamped * jitterFactor;
678
+ const offset = (Math.random() * 2 - 1) * deviation;
679
+ return Math.max(0, clamped + offset);
680
+ }
681
+ function sleep(ms) {
682
+ if (ms <= 0) return Promise.resolve();
683
+ return new Promise((resolve3) => {
684
+ setTimeout(resolve3, ms);
685
+ });
686
+ }
687
+ async function withRetry(config, fn) {
688
+ const retries = Math.max(0, Math.trunc(config.retries));
689
+ const shouldRetry = config.shouldRetry ?? defaultShouldRetry;
690
+ const resolvedConfig = {
691
+ baseDelayMs: config.baseDelayMs ?? 100,
692
+ maxDelayMs: config.maxDelayMs ?? 1e4,
693
+ backoff: config.backoff ?? "exponential",
694
+ jitter: config.jitter ?? false
695
+ };
696
+ for (let attempts = 0; attempts <= retries; attempts += 1) {
697
+ try {
698
+ return await fn();
699
+ } catch (error) {
700
+ if (attempts >= retries) {
701
+ throw error;
702
+ }
703
+ const currentAttempt = attempts + 1;
704
+ const retry = await shouldRetry(error, currentAttempt);
705
+ if (!retry) {
706
+ throw error;
707
+ }
708
+ const delay = computeDelayMs(currentAttempt, error, resolvedConfig);
709
+ await sleep(delay);
710
+ }
711
+ }
712
+ throw new Error("withRetry reached an unexpected state");
713
+ }
666
714
 
667
715
  // src/generator/schema-selection.ts
668
716
  var DEFAULT_POSTGRES_SCHEMAS = ["public"];
@@ -1430,12 +1478,47 @@ function buildAthenaGatewayUrl(baseUrl, path) {
1430
1478
  return `${baseUrl}${path}`;
1431
1479
  }
1432
1480
 
1481
+ // src/cookies/cookie-utils.ts
1482
+ var SECURE_COOKIE_PREFIX = "__Secure-";
1483
+ function parseCookies(cookieHeader) {
1484
+ const cookies = cookieHeader.split("; ");
1485
+ const cookieMap = /* @__PURE__ */ new Map();
1486
+ cookies.forEach((cookie) => {
1487
+ const [name, value] = cookie.split(/=(.*)/s);
1488
+ cookieMap.set(name, value);
1489
+ });
1490
+ return cookieMap;
1491
+ }
1492
+ var getSessionCookie = (request, config) => {
1493
+ const cookies = (request instanceof Headers || !("headers" in request) ? request : request.headers).get("cookie");
1494
+ if (!cookies) {
1495
+ return null;
1496
+ }
1497
+ const { cookieName = "session_token", cookiePrefix = "athena-auth" } = {};
1498
+ const parsedCookie = parseCookies(cookies);
1499
+ const getCookie = (name) => parsedCookie.get(name) || parsedCookie.get(`${SECURE_COOKIE_PREFIX}${name}`);
1500
+ const sessionToken = getCookie(`${cookiePrefix}.${cookieName}`) || getCookie(`${cookiePrefix}-${cookieName}`);
1501
+ if (sessionToken) {
1502
+ return sessionToken;
1503
+ }
1504
+ return null;
1505
+ };
1506
+
1507
+ // package.json
1508
+ var package_default = {
1509
+ version: "2.6.0"
1510
+ };
1511
+
1512
+ // src/sdk-version.ts
1513
+ var PACKAGE_VERSION = package_default.version;
1514
+ function buildSdkHeaderValue(sdkName) {
1515
+ return `${sdkName} ${PACKAGE_VERSION}`;
1516
+ }
1517
+
1433
1518
  // src/gateway/client.ts
1434
1519
  var DEFAULT_CLIENT = "railway_direct";
1435
- var FALLBACK_SDK_VERSION = "1.3.0";
1436
1520
  var SDK_NAME = "xylex-group/athena";
1437
- var SDK_VERSION = typeof process !== "undefined" && process?.env?.npm_package_version ? process.env.npm_package_version : FALLBACK_SDK_VERSION;
1438
- var SDK_HEADER_VALUE = `${SDK_NAME} ${SDK_VERSION}`;
1521
+ var SDK_HEADER_VALUE = buildSdkHeaderValue(SDK_NAME);
1439
1522
  function parseResponseBody(rawText, contentType) {
1440
1523
  if (!rawText) {
1441
1524
  return { parsed: null, parseFailed: false };
@@ -1454,6 +1537,37 @@ function parseResponseBody(rawText, contentType) {
1454
1537
  function normalizeHeaderValue(value) {
1455
1538
  return value ? value : void 0;
1456
1539
  }
1540
+ function resolveHeaderValue(headers, candidates) {
1541
+ for (const candidate of candidates) {
1542
+ const direct = normalizeHeaderValue(headers[candidate]);
1543
+ if (direct) return direct;
1544
+ }
1545
+ const loweredCandidates = new Set(candidates.map((candidate) => candidate.toLowerCase()));
1546
+ for (const [key, value] of Object.entries(headers)) {
1547
+ if (!loweredCandidates.has(key.toLowerCase())) {
1548
+ continue;
1549
+ }
1550
+ const normalized = normalizeHeaderValue(value);
1551
+ if (normalized) return normalized;
1552
+ }
1553
+ return void 0;
1554
+ }
1555
+ function resolveBearerTokenFromAuthorizationHeader(headers) {
1556
+ const authorization = resolveHeaderValue(headers, ["Authorization"]);
1557
+ if (!authorization) {
1558
+ return void 0;
1559
+ }
1560
+ const match = authorization.match(/^Bearer\s+(.+)$/i);
1561
+ const token = match?.[1]?.trim();
1562
+ return token ? token : void 0;
1563
+ }
1564
+ function resolveSessionTokenFromCookieHeader(headers) {
1565
+ const cookie = resolveHeaderValue(headers, ["Cookie"]);
1566
+ if (!cookie) {
1567
+ return void 0;
1568
+ }
1569
+ return getSessionCookie(new Headers({ cookie })) ?? void 0;
1570
+ }
1457
1571
  function isRecord2(value) {
1458
1572
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1459
1573
  }
@@ -1571,7 +1685,7 @@ function buildRpcGetEndpoint(payload) {
1571
1685
  status: 0
1572
1686
  });
1573
1687
  }
1574
- query.set(filter.column, toRpcFilterQueryValue(filter));
1688
+ query.append(filter.column, toRpcFilterQueryValue(filter));
1575
1689
  }
1576
1690
  }
1577
1691
  const endpoint = `/rpc/${encodeURIComponent(functionName)}`;
@@ -1617,6 +1731,20 @@ function buildHeaders(config, options) {
1617
1731
  headers["apikey"] = finalApiKey;
1618
1732
  headers["x-api-key"] = headers["x-api-key"] ?? finalApiKey;
1619
1733
  }
1734
+ const explicitSessionToken = resolveHeaderValue(extraHeaders, [
1735
+ "X-Athena-Auth-Session-Token"
1736
+ ]);
1737
+ const derivedSessionToken = explicitSessionToken ?? resolveSessionTokenFromCookieHeader(extraHeaders);
1738
+ if (derivedSessionToken) {
1739
+ headers["X-Athena-Auth-Session-Token"] = derivedSessionToken;
1740
+ }
1741
+ const explicitBearerToken = resolveHeaderValue(extraHeaders, [
1742
+ "X-Athena-Auth-Bearer-Token"
1743
+ ]);
1744
+ const derivedBearerToken = explicitBearerToken ?? resolveBearerTokenFromAuthorizationHeader(extraHeaders);
1745
+ if (derivedBearerToken) {
1746
+ headers["X-Athena-Auth-Bearer-Token"] = derivedBearerToken;
1747
+ }
1620
1748
  const athenaClientKeys = ["x-athena-client", "X-Athena-Client"];
1621
1749
  Object.entries(extraHeaders).forEach(([key, value]) => {
1622
1750
  if (athenaClientKeys.includes(key)) return;
@@ -2251,10 +2379,8 @@ async function resolveReactEmailPayloadFields(input, fields, options) {
2251
2379
 
2252
2380
  // src/auth/client.ts
2253
2381
  var DEFAULT_AUTH_BASE_URL = "http://localhost:3001/api/auth";
2254
- var FALLBACK_SDK_VERSION2 = "1.0.0";
2255
2382
  var SDK_NAME2 = "xylex-group/athena-auth";
2256
- var SDK_VERSION2 = typeof process !== "undefined" && process?.env?.npm_package_version ? process.env.npm_package_version : FALLBACK_SDK_VERSION2;
2257
- var SDK_HEADER_VALUE2 = `${SDK_NAME2} ${SDK_VERSION2}`;
2383
+ var SDK_HEADER_VALUE2 = buildSdkHeaderValue(SDK_NAME2);
2258
2384
  function normalizeBaseUrl(baseUrl) {
2259
2385
  return (baseUrl ?? DEFAULT_AUTH_BASE_URL).replace(/\/$/, "");
2260
2386
  }
@@ -3355,6 +3481,684 @@ function createDbModule(input) {
3355
3481
  return db;
3356
3482
  }
3357
3483
 
3484
+ // src/storage/module.ts
3485
+ var storageSdkManifest = {
3486
+ methods: [
3487
+ {
3488
+ name: "listStorageCatalogs",
3489
+ method: "GET",
3490
+ path: "/storage/catalogs",
3491
+ responseEnvelope: "raw",
3492
+ responseType: "{ data: S3CatalogItem[] }"
3493
+ },
3494
+ {
3495
+ name: "createStorageCatalog",
3496
+ method: "POST",
3497
+ path: "/storage/catalogs",
3498
+ requestType: "CreateStorageCatalogRequest",
3499
+ responseEnvelope: "raw",
3500
+ responseType: "S3CatalogItem"
3501
+ },
3502
+ {
3503
+ name: "updateStorageCatalog",
3504
+ method: "PATCH",
3505
+ path: "/storage/catalogs/{id}",
3506
+ pathParams: ["id"],
3507
+ requestType: "UpdateStorageCatalogRequest",
3508
+ responseEnvelope: "raw",
3509
+ responseType: "S3CatalogItem"
3510
+ },
3511
+ {
3512
+ name: "deleteStorageCatalog",
3513
+ method: "DELETE",
3514
+ path: "/storage/catalogs/{id}",
3515
+ pathParams: ["id"],
3516
+ responseEnvelope: "raw",
3517
+ responseType: "{ id: string; deleted: boolean }"
3518
+ },
3519
+ {
3520
+ name: "listStorageCredentials",
3521
+ method: "GET",
3522
+ path: "/storage/credentials",
3523
+ responseEnvelope: "raw",
3524
+ responseType: "{ data: S3CredentialListItem[] }"
3525
+ },
3526
+ {
3527
+ name: "createStorageUploadUrl",
3528
+ method: "POST",
3529
+ path: "/storage/files/upload-url",
3530
+ requestType: "CreateStorageUploadUrlRequest",
3531
+ responseEnvelope: "athena",
3532
+ responseType: "StorageUploadUrlResponse"
3533
+ },
3534
+ {
3535
+ name: "createStorageUploadUrls",
3536
+ method: "POST",
3537
+ path: "/storage/files/upload-urls",
3538
+ requestType: "CreateStorageUploadUrlsRequest",
3539
+ responseEnvelope: "athena",
3540
+ responseType: "StorageBatchUploadUrlResponse"
3541
+ },
3542
+ {
3543
+ name: "listStorageFiles",
3544
+ method: "POST",
3545
+ path: "/storage/files/list",
3546
+ requestType: "ListStorageFilesRequest",
3547
+ responseEnvelope: "athena",
3548
+ responseType: "StorageListFilesResponse"
3549
+ },
3550
+ {
3551
+ name: "getStorageFile",
3552
+ method: "GET",
3553
+ path: "/storage/files/{file_id}",
3554
+ pathParams: ["file_id"],
3555
+ responseEnvelope: "athena",
3556
+ responseType: "StorageFileMutationResponse"
3557
+ },
3558
+ {
3559
+ name: "getStorageFileUrl",
3560
+ method: "GET",
3561
+ path: "/storage/files/{file_id}/url",
3562
+ pathParams: ["file_id"],
3563
+ queryParams: ["purpose"],
3564
+ responseEnvelope: "athena",
3565
+ responseType: "PresignedFileUrlResponse"
3566
+ },
3567
+ {
3568
+ name: "getStorageFileProxy",
3569
+ method: "GET",
3570
+ path: "/storage/files/{file_id}/proxy",
3571
+ pathParams: ["file_id"],
3572
+ queryParams: ["purpose"],
3573
+ responseEnvelope: "raw",
3574
+ responseType: "Response",
3575
+ binary: true
3576
+ },
3577
+ {
3578
+ name: "updateStorageFile",
3579
+ method: "PATCH",
3580
+ path: "/storage/files/{file_id}",
3581
+ pathParams: ["file_id"],
3582
+ requestType: "UpdateStorageFileRequest",
3583
+ responseEnvelope: "athena",
3584
+ responseType: "StorageFileMutationResponse"
3585
+ },
3586
+ {
3587
+ name: "deleteStorageFile",
3588
+ method: "DELETE",
3589
+ path: "/storage/files/{file_id}",
3590
+ pathParams: ["file_id"],
3591
+ responseEnvelope: "athena",
3592
+ responseType: "StorageFileMutationResponse"
3593
+ },
3594
+ {
3595
+ name: "setStorageFileVisibility",
3596
+ method: "PATCH",
3597
+ path: "/storage/files/{file_id}/visibility",
3598
+ pathParams: ["file_id"],
3599
+ requestType: "SetStorageFileVisibilityRequest",
3600
+ responseEnvelope: "athena",
3601
+ responseType: "StorageFileMutationResponse"
3602
+ },
3603
+ {
3604
+ name: "deleteStorageFolder",
3605
+ method: "POST",
3606
+ path: "/storage/folders/delete",
3607
+ requestType: "DeleteStorageFolderRequest",
3608
+ responseEnvelope: "athena",
3609
+ responseType: "StorageFolderMutationResponse"
3610
+ },
3611
+ {
3612
+ name: "moveStorageFolder",
3613
+ method: "POST",
3614
+ path: "/storage/folders/move",
3615
+ requestType: "MoveStorageFolderRequest",
3616
+ responseEnvelope: "athena",
3617
+ responseType: "StorageFolderMutationResponse"
3618
+ }
3619
+ ]
3620
+ };
3621
+ var AthenaStorageError = class extends Error {
3622
+ code;
3623
+ athenaCode;
3624
+ kind;
3625
+ category;
3626
+ retryable;
3627
+ status;
3628
+ endpoint;
3629
+ method;
3630
+ requestId;
3631
+ hint;
3632
+ causeDetail;
3633
+ raw;
3634
+ normalized;
3635
+ __athenaNormalizedError;
3636
+ constructor(input) {
3637
+ super(input.message, { cause: input.cause });
3638
+ this.name = "AthenaStorageError";
3639
+ this.code = input.code;
3640
+ this.status = input.status;
3641
+ this.endpoint = input.endpoint;
3642
+ this.method = input.method;
3643
+ this.requestId = input.requestId;
3644
+ this.hint = input.hint;
3645
+ this.causeDetail = causeToString(input.cause);
3646
+ this.raw = input.raw ?? null;
3647
+ this.normalized = normalizeStorageErrorInput(input);
3648
+ this.__athenaNormalizedError = this.normalized;
3649
+ this.athenaCode = this.normalized.code;
3650
+ this.kind = this.normalized.kind;
3651
+ this.category = this.normalized.category;
3652
+ this.retryable = this.normalized.retryable;
3653
+ Object.defineProperty(this, "__athenaNormalizedError", {
3654
+ value: this.normalized,
3655
+ enumerable: false,
3656
+ configurable: false,
3657
+ writable: false
3658
+ });
3659
+ }
3660
+ toDetails() {
3661
+ return {
3662
+ code: this.code,
3663
+ athenaCode: this.athenaCode,
3664
+ kind: this.kind,
3665
+ category: this.category,
3666
+ retryable: this.retryable,
3667
+ message: this.message,
3668
+ status: this.status,
3669
+ endpoint: this.endpoint,
3670
+ method: this.method,
3671
+ requestId: this.requestId,
3672
+ hint: this.hint,
3673
+ cause: this.causeDetail,
3674
+ raw: this.raw
3675
+ };
3676
+ }
3677
+ };
3678
+ function isRecord5(value) {
3679
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
3680
+ }
3681
+ function causeToString(cause) {
3682
+ if (cause === void 0 || cause === null) return void 0;
3683
+ if (typeof cause === "string") return cause;
3684
+ if (cause instanceof Error && cause.message.trim()) return cause.message.trim();
3685
+ try {
3686
+ return JSON.stringify(cause);
3687
+ } catch {
3688
+ return String(cause);
3689
+ }
3690
+ }
3691
+ function storageGatewayCode(code) {
3692
+ if (code === "INVALID_URL") return "INVALID_URL";
3693
+ if (code === "NETWORK_ERROR") return "NETWORK_ERROR";
3694
+ if (code === "INVALID_JSON" || code === "INVALID_ATHENA_ENVELOPE") return "INVALID_JSON";
3695
+ if (code === "HTTP_ERROR") return "HTTP_ERROR";
3696
+ return "UNKNOWN_ERROR";
3697
+ }
3698
+ function headerValue(headers, names) {
3699
+ for (const name of names) {
3700
+ const value = headers.get(name);
3701
+ if (value?.trim()) return value.trim();
3702
+ }
3703
+ return void 0;
3704
+ }
3705
+ function storageOperationFromEndpoint(endpoint, method) {
3706
+ const endpointPath = String(endpoint).split("?")[0];
3707
+ for (const candidate of storageSdkManifest.methods) {
3708
+ if (candidate.method !== method) continue;
3709
+ const pattern = `^${candidate.path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\{[^/]+\\\}/g, "[^/]+")}$`;
3710
+ if (new RegExp(pattern).test(endpointPath)) {
3711
+ return candidate.name;
3712
+ }
3713
+ }
3714
+ return `storage:${method.toLowerCase()}`;
3715
+ }
3716
+ function normalizeStorageErrorInput(input) {
3717
+ return normalizeAthenaError(
3718
+ {
3719
+ data: null,
3720
+ error: {
3721
+ message: input.message,
3722
+ gatewayCode: storageGatewayCode(input.code),
3723
+ status: input.status,
3724
+ raw: input.raw ?? input.cause ?? null
3725
+ },
3726
+ errorDetails: {
3727
+ code: storageGatewayCode(input.code),
3728
+ message: input.message,
3729
+ status: input.status,
3730
+ endpoint: input.endpoint,
3731
+ method: input.method,
3732
+ requestId: input.requestId,
3733
+ hint: input.hint,
3734
+ cause: causeToString(input.cause)
3735
+ },
3736
+ raw: input.raw ?? input.cause ?? null,
3737
+ status: input.status
3738
+ },
3739
+ { operation: storageOperationFromEndpoint(input.endpoint, input.method) }
3740
+ );
3741
+ }
3742
+ function createAthenaStorageError(input) {
3743
+ return new AthenaStorageError(input);
3744
+ }
3745
+ async function notifyStorageError(error, options, runtimeOptions) {
3746
+ const handlers = [runtimeOptions?.onError, options?.onError].filter(
3747
+ (handler) => typeof handler === "function"
3748
+ );
3749
+ for (const handler of handlers) {
3750
+ try {
3751
+ await handler(error);
3752
+ } catch {
3753
+ }
3754
+ }
3755
+ }
3756
+ async function rejectStorageError(input, options, runtimeOptions) {
3757
+ const error = createAthenaStorageError(input);
3758
+ await notifyStorageError(error, options, runtimeOptions);
3759
+ throw error;
3760
+ }
3761
+ function parseResponseBody3(rawText, contentType) {
3762
+ if (!rawText) {
3763
+ return { parsed: null, parseFailed: false };
3764
+ }
3765
+ const contentTypeSuggestsJson = contentType?.toLowerCase().includes("application/json") ?? false;
3766
+ const looksJson = contentTypeSuggestsJson || rawText.startsWith("{") || rawText.startsWith("[");
3767
+ if (!looksJson) {
3768
+ return { parsed: rawText, parseFailed: false };
3769
+ }
3770
+ try {
3771
+ return { parsed: JSON.parse(rawText), parseFailed: false };
3772
+ } catch {
3773
+ return { parsed: rawText, parseFailed: true };
3774
+ }
3775
+ }
3776
+ function appendQuery(path, query) {
3777
+ if (!query) return path;
3778
+ const params = new URLSearchParams();
3779
+ for (const [key, value] of Object.entries(query)) {
3780
+ if (value === void 0 || value === null) continue;
3781
+ params.set(key, String(value));
3782
+ }
3783
+ const queryText = params.toString();
3784
+ return queryText ? `${path}?${queryText}` : path;
3785
+ }
3786
+ function storagePath(path) {
3787
+ return path;
3788
+ }
3789
+ function withPathParam(path, name, value) {
3790
+ return path.replace(`{${name}}`, encodeURIComponent(value));
3791
+ }
3792
+ function resolveErrorMessage3(payload, fallback) {
3793
+ if (isRecord5(payload)) {
3794
+ const message = payload.message ?? payload.error ?? payload.details;
3795
+ if (typeof message === "string" && message.trim()) {
3796
+ return message.trim();
3797
+ }
3798
+ }
3799
+ if (typeof payload === "string" && payload.trim()) {
3800
+ return payload.trim();
3801
+ }
3802
+ return fallback;
3803
+ }
3804
+ function resolveErrorHint2(payload) {
3805
+ if (!isRecord5(payload)) return void 0;
3806
+ const hint = payload.hint ?? payload.suggestion;
3807
+ return typeof hint === "string" && hint.trim() ? hint.trim() : void 0;
3808
+ }
3809
+ function resolveErrorCause(payload) {
3810
+ if (!isRecord5(payload)) return void 0;
3811
+ const cause = payload.cause ?? payload.reason;
3812
+ return typeof cause === "string" && cause.trim() ? cause.trim() : void 0;
3813
+ }
3814
+ function storageCodeFromUnknown(error) {
3815
+ if (isAthenaGatewayError(error)) {
3816
+ if (error.code === "INVALID_URL") return "INVALID_URL";
3817
+ if (error.code === "NETWORK_ERROR") return "NETWORK_ERROR";
3818
+ if (error.code === "INVALID_JSON") return "INVALID_JSON";
3819
+ if (error.code === "HTTP_ERROR") return "HTTP_ERROR";
3820
+ }
3821
+ return "UNKNOWN_ERROR";
3822
+ }
3823
+ async function callStorageEndpoint(gateway, endpoint, method, envelope, payload, options, runtimeOptions) {
3824
+ let url;
3825
+ let headers;
3826
+ try {
3827
+ const baseUrl = options?.baseUrl ? normalizeAthenaGatewayBaseUrl(options.baseUrl) : gateway.baseUrl;
3828
+ url = buildAthenaGatewayUrl(baseUrl, endpoint);
3829
+ headers = gateway.buildHeaders(options);
3830
+ } catch (error) {
3831
+ return rejectStorageError(
3832
+ {
3833
+ code: storageCodeFromUnknown(error),
3834
+ message: error instanceof Error ? error.message : `Athena storage ${method} ${endpoint} failed before sending the request`,
3835
+ status: isAthenaGatewayError(error) ? error.status : 0,
3836
+ endpoint,
3837
+ method,
3838
+ raw: error,
3839
+ requestId: isAthenaGatewayError(error) ? error.requestId : void 0,
3840
+ hint: isAthenaGatewayError(error) ? error.hint : void 0,
3841
+ cause: error
3842
+ },
3843
+ options,
3844
+ runtimeOptions
3845
+ );
3846
+ }
3847
+ const requestInit = {
3848
+ method,
3849
+ headers,
3850
+ signal: options?.signal
3851
+ };
3852
+ if (payload !== void 0 && method !== "GET") {
3853
+ requestInit.body = JSON.stringify(payload);
3854
+ }
3855
+ let response;
3856
+ try {
3857
+ response = await fetch(url, requestInit);
3858
+ } catch (error) {
3859
+ const message = error instanceof Error ? error.message : String(error);
3860
+ return rejectStorageError(
3861
+ {
3862
+ code: "NETWORK_ERROR",
3863
+ message: `Network error while calling Athena storage ${method} ${endpoint}: ${message}`,
3864
+ status: 0,
3865
+ endpoint,
3866
+ method,
3867
+ cause: error
3868
+ },
3869
+ options,
3870
+ runtimeOptions
3871
+ );
3872
+ }
3873
+ let rawText;
3874
+ try {
3875
+ rawText = await response.text();
3876
+ } catch (error) {
3877
+ return rejectStorageError(
3878
+ {
3879
+ code: "NETWORK_ERROR",
3880
+ message: `Athena storage ${method} ${endpoint} response body could not be read`,
3881
+ status: response.status,
3882
+ endpoint,
3883
+ method,
3884
+ requestId: headerValue(response.headers, ["x-athena-request-id", "x-request-id", "request-id"]),
3885
+ cause: error
3886
+ },
3887
+ options,
3888
+ runtimeOptions
3889
+ );
3890
+ }
3891
+ const parsedBody = parseResponseBody3(rawText ?? "", response.headers.get("content-type"));
3892
+ const requestId = headerValue(response.headers, ["x-athena-request-id", "x-request-id", "request-id"]);
3893
+ if (parsedBody.parseFailed) {
3894
+ return rejectStorageError(
3895
+ {
3896
+ code: "INVALID_JSON",
3897
+ message: `Athena storage ${method} ${endpoint} returned malformed JSON`,
3898
+ status: response.status,
3899
+ endpoint,
3900
+ method,
3901
+ requestId,
3902
+ raw: parsedBody.parsed
3903
+ },
3904
+ options,
3905
+ runtimeOptions
3906
+ );
3907
+ }
3908
+ if (!response.ok) {
3909
+ return rejectStorageError(
3910
+ {
3911
+ code: "HTTP_ERROR",
3912
+ message: resolveErrorMessage3(
3913
+ parsedBody.parsed,
3914
+ `Athena storage ${method} ${endpoint} failed with status ${response.status}`
3915
+ ),
3916
+ status: response.status,
3917
+ endpoint,
3918
+ method,
3919
+ requestId,
3920
+ hint: resolveErrorHint2(parsedBody.parsed),
3921
+ cause: resolveErrorCause(parsedBody.parsed),
3922
+ raw: parsedBody.parsed
3923
+ },
3924
+ options,
3925
+ runtimeOptions
3926
+ );
3927
+ }
3928
+ if (envelope === "athena") {
3929
+ if (!isRecord5(parsedBody.parsed) || !("data" in parsedBody.parsed)) {
3930
+ return rejectStorageError(
3931
+ {
3932
+ code: "INVALID_ATHENA_ENVELOPE",
3933
+ message: `Athena storage ${method} ${endpoint} returned an invalid Athena envelope`,
3934
+ status: response.status,
3935
+ endpoint,
3936
+ method,
3937
+ requestId,
3938
+ raw: parsedBody.parsed
3939
+ },
3940
+ options,
3941
+ runtimeOptions
3942
+ );
3943
+ }
3944
+ return parsedBody.parsed.data;
3945
+ }
3946
+ return parsedBody.parsed;
3947
+ }
3948
+ async function callStorageBinaryEndpoint(gateway, endpoint, method, options, runtimeOptions) {
3949
+ let url;
3950
+ let headers;
3951
+ try {
3952
+ const baseUrl = options?.baseUrl ? normalizeAthenaGatewayBaseUrl(options.baseUrl) : gateway.baseUrl;
3953
+ url = buildAthenaGatewayUrl(baseUrl, endpoint);
3954
+ headers = gateway.buildHeaders(options);
3955
+ } catch (error) {
3956
+ return rejectStorageError(
3957
+ {
3958
+ code: storageCodeFromUnknown(error),
3959
+ message: error instanceof Error ? error.message : `Athena storage ${method} ${endpoint} failed before sending the request`,
3960
+ status: isAthenaGatewayError(error) ? error.status : 0,
3961
+ endpoint,
3962
+ method,
3963
+ raw: error,
3964
+ requestId: isAthenaGatewayError(error) ? error.requestId : void 0,
3965
+ hint: isAthenaGatewayError(error) ? error.hint : void 0,
3966
+ cause: error
3967
+ },
3968
+ options,
3969
+ runtimeOptions
3970
+ );
3971
+ }
3972
+ let response;
3973
+ try {
3974
+ response = await fetch(url, {
3975
+ method,
3976
+ headers,
3977
+ signal: options?.signal
3978
+ });
3979
+ } catch (error) {
3980
+ const message = error instanceof Error ? error.message : String(error);
3981
+ return rejectStorageError(
3982
+ {
3983
+ code: "NETWORK_ERROR",
3984
+ message: `Network error while calling Athena storage ${method} ${endpoint}: ${message}`,
3985
+ status: 0,
3986
+ endpoint,
3987
+ method,
3988
+ cause: error
3989
+ },
3990
+ options,
3991
+ runtimeOptions
3992
+ );
3993
+ }
3994
+ if (response.ok) {
3995
+ return response;
3996
+ }
3997
+ const requestId = headerValue(response.headers, ["x-athena-request-id", "x-request-id", "request-id"]);
3998
+ let rawErrorBody = null;
3999
+ try {
4000
+ const rawText = await response.text();
4001
+ const parsedBody = parseResponseBody3(rawText ?? "", response.headers.get("content-type"));
4002
+ rawErrorBody = parsedBody.parsed;
4003
+ } catch (error) {
4004
+ return rejectStorageError(
4005
+ {
4006
+ code: "NETWORK_ERROR",
4007
+ message: `Athena storage ${method} ${endpoint} error response body could not be read`,
4008
+ status: response.status,
4009
+ endpoint,
4010
+ method,
4011
+ requestId,
4012
+ cause: error
4013
+ },
4014
+ options,
4015
+ runtimeOptions
4016
+ );
4017
+ }
4018
+ return rejectStorageError(
4019
+ {
4020
+ code: "HTTP_ERROR",
4021
+ message: resolveErrorMessage3(
4022
+ rawErrorBody,
4023
+ `Athena storage ${method} ${endpoint} failed with status ${response.status}`
4024
+ ),
4025
+ status: response.status,
4026
+ endpoint,
4027
+ method,
4028
+ requestId,
4029
+ hint: resolveErrorHint2(rawErrorBody),
4030
+ cause: resolveErrorCause(rawErrorBody),
4031
+ raw: rawErrorBody
4032
+ },
4033
+ options,
4034
+ runtimeOptions
4035
+ );
4036
+ }
4037
+ function createStorageModule(gateway, runtimeOptions) {
4038
+ return {
4039
+ listStorageCatalogs(options) {
4040
+ return callStorageEndpoint(gateway, storagePath("/storage/catalogs"), "GET", "raw", void 0, options, runtimeOptions);
4041
+ },
4042
+ createStorageCatalog(input, options) {
4043
+ return callStorageEndpoint(gateway, storagePath("/storage/catalogs"), "POST", "raw", input, options, runtimeOptions);
4044
+ },
4045
+ updateStorageCatalog(id, input, options) {
4046
+ return callStorageEndpoint(
4047
+ gateway,
4048
+ storagePath(withPathParam("/storage/catalogs/{id}", "id", id)),
4049
+ "PATCH",
4050
+ "raw",
4051
+ input,
4052
+ options,
4053
+ runtimeOptions
4054
+ );
4055
+ },
4056
+ deleteStorageCatalog(id, options) {
4057
+ return callStorageEndpoint(
4058
+ gateway,
4059
+ storagePath(withPathParam("/storage/catalogs/{id}", "id", id)),
4060
+ "DELETE",
4061
+ "raw",
4062
+ void 0,
4063
+ options,
4064
+ runtimeOptions
4065
+ );
4066
+ },
4067
+ listStorageCredentials(options) {
4068
+ return callStorageEndpoint(gateway, storagePath("/storage/credentials"), "GET", "raw", void 0, options, runtimeOptions);
4069
+ },
4070
+ createStorageUploadUrl(input, options) {
4071
+ return callStorageEndpoint(
4072
+ gateway,
4073
+ storagePath("/storage/files/upload-url"),
4074
+ "POST",
4075
+ "athena",
4076
+ input,
4077
+ options,
4078
+ runtimeOptions
4079
+ );
4080
+ },
4081
+ createStorageUploadUrls(input, options) {
4082
+ return callStorageEndpoint(
4083
+ gateway,
4084
+ storagePath("/storage/files/upload-urls"),
4085
+ "POST",
4086
+ "athena",
4087
+ input,
4088
+ options,
4089
+ runtimeOptions
4090
+ );
4091
+ },
4092
+ listStorageFiles(input, options) {
4093
+ return callStorageEndpoint(gateway, storagePath("/storage/files/list"), "POST", "athena", input, options, runtimeOptions);
4094
+ },
4095
+ getStorageFile(fileId, options) {
4096
+ return callStorageEndpoint(
4097
+ gateway,
4098
+ storagePath(withPathParam("/storage/files/{file_id}", "file_id", fileId)),
4099
+ "GET",
4100
+ "athena",
4101
+ void 0,
4102
+ options,
4103
+ runtimeOptions
4104
+ );
4105
+ },
4106
+ getStorageFileUrl(fileId, query, options) {
4107
+ const path = appendQuery(
4108
+ withPathParam("/storage/files/{file_id}/url", "file_id", fileId),
4109
+ query
4110
+ );
4111
+ return callStorageEndpoint(gateway, storagePath(path), "GET", "athena", void 0, options, runtimeOptions);
4112
+ },
4113
+ getStorageFileProxy(fileId, query, options) {
4114
+ const path = appendQuery(
4115
+ withPathParam("/storage/files/{file_id}/proxy", "file_id", fileId),
4116
+ query
4117
+ );
4118
+ return callStorageBinaryEndpoint(gateway, storagePath(path), "GET", options, runtimeOptions);
4119
+ },
4120
+ updateStorageFile(fileId, input, options) {
4121
+ return callStorageEndpoint(
4122
+ gateway,
4123
+ storagePath(withPathParam("/storage/files/{file_id}", "file_id", fileId)),
4124
+ "PATCH",
4125
+ "athena",
4126
+ input,
4127
+ options,
4128
+ runtimeOptions
4129
+ );
4130
+ },
4131
+ deleteStorageFile(fileId, options) {
4132
+ return callStorageEndpoint(
4133
+ gateway,
4134
+ storagePath(withPathParam("/storage/files/{file_id}", "file_id", fileId)),
4135
+ "DELETE",
4136
+ "athena",
4137
+ void 0,
4138
+ options,
4139
+ runtimeOptions
4140
+ );
4141
+ },
4142
+ setStorageFileVisibility(fileId, input, options) {
4143
+ return callStorageEndpoint(
4144
+ gateway,
4145
+ storagePath(withPathParam("/storage/files/{file_id}/visibility", "file_id", fileId)),
4146
+ "PATCH",
4147
+ "athena",
4148
+ input,
4149
+ options,
4150
+ runtimeOptions
4151
+ );
4152
+ },
4153
+ deleteStorageFolder(input, options) {
4154
+ return callStorageEndpoint(gateway, storagePath("/storage/folders/delete"), "POST", "athena", input, options, runtimeOptions);
4155
+ },
4156
+ moveStorageFolder(input, options) {
4157
+ return callStorageEndpoint(gateway, storagePath("/storage/folders/move"), "POST", "athena", input, options, runtimeOptions);
4158
+ }
4159
+ };
4160
+ }
4161
+
3358
4162
  // src/query-ast.ts
3359
4163
  var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
3360
4164
  var FILTER_OPERATORS = /* @__PURE__ */ new Set([
@@ -3382,7 +4186,7 @@ var BOOLEAN_SAFE_OPERATORS = /* @__PURE__ */ new Set([
3382
4186
  "ilike",
3383
4187
  "is"
3384
4188
  ]);
3385
- function isRecord5(value) {
4189
+ function isRecord6(value) {
3386
4190
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
3387
4191
  }
3388
4192
  function isUuidString(value) {
@@ -3395,7 +4199,7 @@ function shouldUseUuidTextComparison(column, value) {
3395
4199
  return typeof value === "string" && isUuidString(value) && isUuidIdentifierColumn(column);
3396
4200
  }
3397
4201
  function isRelationSelectNode(value) {
3398
- return isRecord5(value) && isRecord5(value.select);
4202
+ return isRecord6(value) && isRecord6(value.select);
3399
4203
  }
3400
4204
  function normalizeIdentifier(value, label) {
3401
4205
  const normalized = value.trim();
@@ -3451,7 +4255,7 @@ function compileRelationToken(key, node) {
3451
4255
  return `${prefix}${relationToken}(${nested})`;
3452
4256
  }
3453
4257
  function compileSelectShape(select) {
3454
- if (!isRecord5(select)) {
4258
+ if (!isRecord6(select)) {
3455
4259
  throw new Error("findMany select must be an object");
3456
4260
  }
3457
4261
  const tokens = [];
@@ -3475,7 +4279,7 @@ function compileSelectShape(select) {
3475
4279
  return tokens.join(",");
3476
4280
  }
3477
4281
  function selectShapeUsesRelationSchema(select) {
3478
- if (!isRecord5(select)) {
4282
+ if (!isRecord6(select)) {
3479
4283
  return false;
3480
4284
  }
3481
4285
  for (const rawValue of Object.values(select)) {
@@ -3493,7 +4297,7 @@ function selectShapeUsesRelationSchema(select) {
3493
4297
  }
3494
4298
  function compileColumnWhere(column, input) {
3495
4299
  const normalizedColumn = normalizeIdentifier(column, "where column");
3496
- if (!isRecord5(input)) {
4300
+ if (!isRecord6(input)) {
3497
4301
  return [buildGatewayCondition("eq", normalizedColumn, input)];
3498
4302
  }
3499
4303
  const conditions = [];
@@ -3521,7 +4325,7 @@ function compileColumnWhere(column, input) {
3521
4325
  return conditions;
3522
4326
  }
3523
4327
  function compileBooleanExpressionTerms(clause, label) {
3524
- if (!isRecord5(clause)) {
4328
+ if (!isRecord6(clause)) {
3525
4329
  throw new Error(`findMany where.${label} clauses must be objects`);
3526
4330
  }
3527
4331
  const entries = Object.entries(clause).filter(([, value]) => value !== void 0);
@@ -3530,7 +4334,7 @@ function compileBooleanExpressionTerms(clause, label) {
3530
4334
  }
3531
4335
  const [rawColumn, rawValue] = entries[0];
3532
4336
  const column = normalizeIdentifier(rawColumn, `where.${label} column`);
3533
- if (!isRecord5(rawValue)) {
4337
+ if (!isRecord6(rawValue)) {
3534
4338
  return [`${column}.eq.${stringifyFilterValue(rawValue)}`];
3535
4339
  }
3536
4340
  const operatorEntries = Object.entries(rawValue).filter(([, value]) => value !== void 0);
@@ -3554,7 +4358,7 @@ function compileWhere(where) {
3554
4358
  if (where === void 0) {
3555
4359
  return void 0;
3556
4360
  }
3557
- if (!isRecord5(where)) {
4361
+ if (!isRecord6(where)) {
3558
4362
  throw new Error("findMany where must be an object");
3559
4363
  }
3560
4364
  const conditions = [];
@@ -3604,7 +4408,7 @@ function compileOrderBy(orderBy) {
3604
4408
  if (orderBy === void 0) {
3605
4409
  return void 0;
3606
4410
  }
3607
- if (!isRecord5(orderBy)) {
4411
+ if (!isRecord6(orderBy)) {
3608
4412
  throw new Error("findMany orderBy must be an object");
3609
4413
  }
3610
4414
  if ("column" in orderBy) {
@@ -3700,7 +4504,7 @@ function buildStructuredWhere(conditions) {
3700
4504
  if (!condition.column) {
3701
4505
  return null;
3702
4506
  }
3703
- if (condition.column_cast !== void 0 || condition.value_cast !== void 0) {
4507
+ if (condition.value_cast !== void 0) {
3704
4508
  return null;
3705
4509
  }
3706
4510
  const operand = condition.value;
@@ -3779,6 +4583,104 @@ function toFindManyAstOrder(order) {
3779
4583
  ascending: order.direction !== "descending"
3780
4584
  };
3781
4585
  }
4586
+ function isRecord7(value) {
4587
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
4588
+ }
4589
+ function normalizeFindManyAstColumnPredicate(value) {
4590
+ if (!isRecord7(value)) {
4591
+ return {
4592
+ eq: value
4593
+ };
4594
+ }
4595
+ const normalized = {};
4596
+ for (const [key, operand] of Object.entries(value)) {
4597
+ if (operand !== void 0) {
4598
+ normalized[key] = operand;
4599
+ }
4600
+ }
4601
+ return normalized;
4602
+ }
4603
+ function normalizeFindManyAstBooleanOperand(clause) {
4604
+ const normalized = {};
4605
+ for (const [column, value] of Object.entries(clause)) {
4606
+ if (value === void 0) {
4607
+ continue;
4608
+ }
4609
+ normalized[column] = normalizeFindManyAstColumnPredicate(value);
4610
+ }
4611
+ return normalized;
4612
+ }
4613
+ function normalizeFindManyAstWhere(where) {
4614
+ if (!where || !isRecord7(where)) {
4615
+ return where;
4616
+ }
4617
+ const normalized = {};
4618
+ for (const [key, value] of Object.entries(where)) {
4619
+ if (value === void 0) {
4620
+ continue;
4621
+ }
4622
+ if (key === "or" && Array.isArray(value)) {
4623
+ normalized.or = value.map(
4624
+ (clause) => normalizeFindManyAstBooleanOperand(clause)
4625
+ );
4626
+ continue;
4627
+ }
4628
+ if (key === "not" && isRecord7(value)) {
4629
+ normalized.not = normalizeFindManyAstBooleanOperand(
4630
+ value
4631
+ );
4632
+ continue;
4633
+ }
4634
+ normalized[key] = normalizeFindManyAstColumnPredicate(value);
4635
+ }
4636
+ return normalized;
4637
+ }
4638
+ function predicateRequiresUuidQueryFallback(column, value) {
4639
+ if (!isRecord7(value)) {
4640
+ return shouldUseUuidTextComparison(column, value);
4641
+ }
4642
+ const eqValue = value.eq;
4643
+ return eqValue !== void 0 && shouldUseUuidTextComparison(column, eqValue);
4644
+ }
4645
+ function booleanOperandRequiresUuidQueryFallback(clause) {
4646
+ for (const [column, value] of Object.entries(clause)) {
4647
+ if (value === void 0) {
4648
+ continue;
4649
+ }
4650
+ if (predicateRequiresUuidQueryFallback(column, value)) {
4651
+ return true;
4652
+ }
4653
+ }
4654
+ return false;
4655
+ }
4656
+ function findManyAstWhereRequiresLegacyTransport(where) {
4657
+ if (!where || !isRecord7(where)) {
4658
+ return false;
4659
+ }
4660
+ for (const [key, value] of Object.entries(where)) {
4661
+ if (value === void 0) {
4662
+ continue;
4663
+ }
4664
+ if (key === "or" && Array.isArray(value)) {
4665
+ if (value.some(
4666
+ (clause) => booleanOperandRequiresUuidQueryFallback(clause)
4667
+ )) {
4668
+ return true;
4669
+ }
4670
+ continue;
4671
+ }
4672
+ if (key === "not" && isRecord7(value)) {
4673
+ if (booleanOperandRequiresUuidQueryFallback(value)) {
4674
+ return true;
4675
+ }
4676
+ continue;
4677
+ }
4678
+ if (predicateRequiresUuidQueryFallback(key, value)) {
4679
+ return true;
4680
+ }
4681
+ }
4682
+ return false;
4683
+ }
3782
4684
  function resolvePagination(input) {
3783
4685
  let limit = input.limit;
3784
4686
  let offset = input.offset;
@@ -3797,25 +4699,6 @@ function hasTypedEqualityComparison(conditions) {
3797
4699
  }
3798
4700
  function createSelectTransportPlan(input) {
3799
4701
  const conditions = input.state.conditions.length ? input.state.conditions.map((condition) => ({ ...condition })) : void 0;
3800
- if (hasTypedEqualityComparison(conditions) && !input.options?.head && !input.options?.count && conditions) {
3801
- const query = input.buildTypedSelectQuery({
3802
- tableName: input.tableName,
3803
- columns: input.columns,
3804
- conditions,
3805
- limit: input.state.limit,
3806
- offset: input.state.offset,
3807
- currentPage: input.state.currentPage,
3808
- pageSize: input.state.pageSize,
3809
- order: input.state.order
3810
- });
3811
- if (query) {
3812
- return {
3813
- kind: "query",
3814
- query,
3815
- payload: { query }
3816
- };
3817
- }
3818
- }
3819
4702
  const pagination = resolvePagination({
3820
4703
  limit: input.state.limit,
3821
4704
  offset: input.state.offset,
@@ -3851,6 +4734,25 @@ function createSelectTransportPlan(input) {
3851
4734
  }
3852
4735
  };
3853
4736
  }
4737
+ if (hasTypedEqualityComparison(conditions) && !input.options?.head && !input.options?.count && conditions) {
4738
+ const query = input.buildTypedSelectQuery({
4739
+ tableName: input.tableName,
4740
+ columns: input.columns,
4741
+ conditions,
4742
+ limit: input.state.limit,
4743
+ offset: input.state.offset,
4744
+ currentPage: input.state.currentPage,
4745
+ pageSize: input.state.pageSize,
4746
+ order: input.state.order
4747
+ });
4748
+ if (query) {
4749
+ return {
4750
+ kind: "query",
4751
+ query,
4752
+ payload: { query }
4753
+ };
4754
+ }
4755
+ }
3854
4756
  return {
3855
4757
  kind: "fetch",
3856
4758
  payload: {
@@ -3907,6 +4809,13 @@ function formatResult(response) {
3907
4809
  }
3908
4810
  return result;
3909
4811
  }
4812
+ var EXPERIMENTAL_READ_RETRY_CONFIG = {
4813
+ retries: 2,
4814
+ baseDelayMs: 100,
4815
+ maxDelayMs: 1e3,
4816
+ backoff: "exponential",
4817
+ jitter: true
4818
+ };
3910
4819
  function attachNormalizedError(result, normalizedError) {
3911
4820
  Object.defineProperty(result, ATHENA_NORMALIZED_ERROR_KEY, {
3912
4821
  value: normalizedError,
@@ -3933,7 +4842,36 @@ function createResultFormatter(experimental) {
3933
4842
  return result;
3934
4843
  };
3935
4844
  }
3936
- function isRecord6(value) {
4845
+ async function executeExperimentalRead(experimental, runner) {
4846
+ if (!experimental?.retryReads) {
4847
+ return runner();
4848
+ }
4849
+ let lastRetryableResult;
4850
+ let lastRetrySignal = null;
4851
+ try {
4852
+ return await withRetry(
4853
+ {
4854
+ ...EXPERIMENTAL_READ_RETRY_CONFIG,
4855
+ shouldRetry: (error) => error === lastRetrySignal || normalizeAthenaError(error).retryable
4856
+ },
4857
+ async () => {
4858
+ const result = await runner();
4859
+ if (result.error?.retryable) {
4860
+ lastRetryableResult = result;
4861
+ lastRetrySignal = result.error;
4862
+ throw lastRetrySignal;
4863
+ }
4864
+ return result;
4865
+ }
4866
+ );
4867
+ } catch (error) {
4868
+ if (lastRetryableResult && error === lastRetrySignal) {
4869
+ return lastRetryableResult;
4870
+ }
4871
+ throw error;
4872
+ }
4873
+ }
4874
+ function isRecord8(value) {
3937
4875
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
3938
4876
  }
3939
4877
  function firstNonEmptyString2(...values) {
@@ -3945,8 +4883,8 @@ function firstNonEmptyString2(...values) {
3945
4883
  return void 0;
3946
4884
  }
3947
4885
  function resolveStructuredErrorPayload2(raw) {
3948
- if (!isRecord6(raw)) return null;
3949
- return isRecord6(raw.error) ? raw.error : raw;
4886
+ if (!isRecord8(raw)) return null;
4887
+ return isRecord8(raw.error) ? raw.error : raw;
3950
4888
  }
3951
4889
  function resolveStructuredErrorDetails(payload, message) {
3952
4890
  if (!payload || !("details" in payload)) {
@@ -3962,7 +4900,7 @@ function resolveStructuredErrorDetails(payload, message) {
3962
4900
  return details;
3963
4901
  }
3964
4902
  function createResultError(response, result, normalized) {
3965
- const rawRecord = isRecord6(response.raw) ? response.raw : null;
4903
+ const rawRecord = isRecord8(response.raw) ? response.raw : null;
3966
4904
  const payload = resolveStructuredErrorPayload2(response.raw);
3967
4905
  const message = firstNonEmptyString2(
3968
4906
  response.error,
@@ -4157,7 +5095,14 @@ function toSingleResult(response) {
4157
5095
  function mergeOptions(...options) {
4158
5096
  return options.reduce((acc, next) => {
4159
5097
  if (!next) return acc;
4160
- return { ...acc, ...next };
5098
+ const merged = { ...acc ?? {}, ...next };
5099
+ if (acc?.headers || next.headers) {
5100
+ merged.headers = {
5101
+ ...acc?.headers ?? {},
5102
+ ...next.headers ?? {}
5103
+ };
5104
+ }
5105
+ return merged;
4161
5106
  }, void 0);
4162
5107
  }
4163
5108
  function asAthenaJsonObject(value) {
@@ -4949,42 +5894,48 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
4949
5894
  buildTypedSelectQuery
4950
5895
  });
4951
5896
  if (plan.kind === "query") {
4952
- return executeWithQueryTrace(
5897
+ return executeExperimentalRead(
5898
+ experimental,
5899
+ () => executeWithQueryTrace(
5900
+ tracer,
5901
+ {
5902
+ operation: "select",
5903
+ endpoint: "/gateway/query",
5904
+ table: resolvedTableName,
5905
+ sql: plan.query,
5906
+ payload: plan.payload,
5907
+ options
5908
+ },
5909
+ async () => {
5910
+ const queryResponse = await client.queryGateway(plan.payload, options);
5911
+ return formatGatewayResult(queryResponse, { table: resolvedTableName, operation: "select" });
5912
+ },
5913
+ callsite
5914
+ )
5915
+ );
5916
+ }
5917
+ const sql = buildDebugSelectQuery({
5918
+ tableName: resolvedTableName,
5919
+ ...plan.debug
5920
+ });
5921
+ return executeExperimentalRead(
5922
+ experimental,
5923
+ () => executeWithQueryTrace(
4953
5924
  tracer,
4954
5925
  {
4955
5926
  operation: "select",
4956
- endpoint: "/gateway/query",
5927
+ endpoint: "/gateway/fetch",
4957
5928
  table: resolvedTableName,
4958
- sql: plan.query,
5929
+ sql,
4959
5930
  payload: plan.payload,
4960
5931
  options
4961
5932
  },
4962
5933
  async () => {
4963
- const queryResponse = await client.queryGateway(plan.payload, options);
4964
- return formatGatewayResult(queryResponse, { table: resolvedTableName, operation: "select" });
5934
+ const response = await client.fetchGateway(plan.payload, options);
5935
+ return formatGatewayResult(response, { table: resolvedTableName, operation: "select" });
4965
5936
  },
4966
5937
  callsite
4967
- );
4968
- }
4969
- const sql = buildDebugSelectQuery({
4970
- tableName: resolvedTableName,
4971
- ...plan.debug
4972
- });
4973
- return executeWithQueryTrace(
4974
- tracer,
4975
- {
4976
- operation: "select",
4977
- endpoint: "/gateway/fetch",
4978
- table: resolvedTableName,
4979
- sql,
4980
- payload: plan.payload,
4981
- options
4982
- },
4983
- async () => {
4984
- const response = await client.fetchGateway(plan.payload, options);
4985
- return formatGatewayResult(response, { table: resolvedTableName, operation: "select" });
4986
- },
4987
- callsite
5938
+ )
4988
5939
  );
4989
5940
  };
4990
5941
  const createSelectChain = (columns, options, initialCallsite) => {
@@ -5054,14 +6005,14 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
5054
6005
  if (options.limit !== void 0) {
5055
6006
  executionState.limit = options.limit;
5056
6007
  }
5057
- if (experimental?.findManyAst && canUseFindManyAstTransport(baseState) && !selectShapeUsesRelationSchema(options.select)) {
6008
+ if (experimental?.findManyAst && canUseFindManyAstTransport(baseState) && !selectShapeUsesRelationSchema(options.select) && !findManyAstWhereRequiresLegacyTransport(options.where)) {
5058
6009
  const resolvedTableName = resolveTableNameForCall(tableName, void 0);
5059
6010
  const payload = {
5060
6011
  table_name: resolvedTableName,
5061
6012
  select: options.select
5062
6013
  };
5063
6014
  if (options.where !== void 0) {
5064
- payload.where = options.where;
6015
+ payload.where = normalizeFindManyAstWhere(options.where);
5065
6016
  }
5066
6017
  const astOrder = toFindManyAstOrder(executionState.order);
5067
6018
  if (astOrder !== void 0) {
@@ -5077,22 +6028,25 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
5077
6028
  limit: executionState.limit,
5078
6029
  order: executionState.order
5079
6030
  });
5080
- return executeWithQueryTrace(
5081
- tracer,
5082
- {
5083
- operation: "select",
5084
- endpoint: "/gateway/fetch",
5085
- table: resolvedTableName,
5086
- sql,
5087
- payload
5088
- },
5089
- async () => {
5090
- const response = await client.fetchGateway(
6031
+ return executeExperimentalRead(
6032
+ experimental,
6033
+ () => executeWithQueryTrace(
6034
+ tracer,
6035
+ {
6036
+ operation: "select",
6037
+ endpoint: "/gateway/fetch",
6038
+ table: resolvedTableName,
6039
+ sql,
5091
6040
  payload
5092
- );
5093
- return formatGatewayResult(response, { table: resolvedTableName, operation: "select" });
5094
- },
5095
- callsite
6041
+ },
6042
+ async () => {
6043
+ const response = await client.fetchGateway(
6044
+ payload
6045
+ );
6046
+ return formatGatewayResult(response, { table: resolvedTableName, operation: "select" });
6047
+ },
6048
+ callsite
6049
+ )
5096
6050
  );
5097
6051
  }
5098
6052
  return runSelect(
@@ -5340,7 +6294,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
5340
6294
  });
5341
6295
  return builder;
5342
6296
  }
5343
- function createQueryBuilder(client, formatGatewayResult, tracer) {
6297
+ function createQueryBuilder(client, formatGatewayResult, experimental, tracer) {
5344
6298
  return async function query(query, options) {
5345
6299
  const normalizedQuery = query.trim();
5346
6300
  if (!normalizedQuery) {
@@ -5348,30 +6302,39 @@ function createQueryBuilder(client, formatGatewayResult, tracer) {
5348
6302
  }
5349
6303
  const payload = { query: normalizedQuery };
5350
6304
  const callsite = captureTraceCallsite(tracer);
5351
- return executeWithQueryTrace(
5352
- tracer,
5353
- {
5354
- operation: "query",
5355
- endpoint: "/gateway/query",
5356
- sql: normalizedQuery,
5357
- payload,
5358
- options
5359
- },
5360
- async () => {
5361
- const response = await client.queryGateway(payload, options);
5362
- return formatGatewayResult(response, { operation: "query" });
5363
- },
5364
- callsite
6305
+ return executeExperimentalRead(
6306
+ experimental,
6307
+ () => executeWithQueryTrace(
6308
+ tracer,
6309
+ {
6310
+ operation: "query",
6311
+ endpoint: "/gateway/query",
6312
+ sql: normalizedQuery,
6313
+ payload,
6314
+ options
6315
+ },
6316
+ async () => {
6317
+ const response = await client.queryGateway(payload, options);
6318
+ return formatGatewayResult(response, { operation: "query" });
6319
+ },
6320
+ callsite
6321
+ )
5365
6322
  );
5366
6323
  };
5367
6324
  }
5368
6325
  function createClientFromConfig(config) {
6326
+ const gatewayHeaders = {
6327
+ ...config.headers ?? {}
6328
+ };
6329
+ if (config.auth?.bearerToken && gatewayHeaders["X-Athena-Auth-Bearer-Token"] === void 0 && gatewayHeaders["x-athena-auth-bearer-token"] === void 0) {
6330
+ gatewayHeaders["X-Athena-Auth-Bearer-Token"] = config.auth.bearerToken;
6331
+ }
5369
6332
  const gateway = createAthenaGatewayClient({
5370
6333
  baseUrl: config.baseUrl,
5371
6334
  apiKey: config.apiKey,
5372
6335
  client: config.client,
5373
6336
  backend: config.backend,
5374
- headers: config.headers
6337
+ headers: gatewayHeaders
5375
6338
  });
5376
6339
  const formatGatewayResult = createResultFormatter();
5377
6340
  const queryTracer = createQueryTracer(config.experimental);
@@ -5398,9 +6361,9 @@ function createClientFromConfig(config) {
5398
6361
  captureTraceCallsite(queryTracer)
5399
6362
  );
5400
6363
  };
5401
- const query = createQueryBuilder(gateway, formatGatewayResult, queryTracer);
6364
+ const query = createQueryBuilder(gateway, formatGatewayResult, config.experimental, queryTracer);
5402
6365
  const db = createDbModule({ from, rpc, query });
5403
- return {
6366
+ const sdkClient = {
5404
6367
  from,
5405
6368
  db,
5406
6369
  rpc,
@@ -5408,6 +6371,14 @@ function createClientFromConfig(config) {
5408
6371
  verifyConnection: gateway.verifyConnection,
5409
6372
  auth: auth.auth
5410
6373
  };
6374
+ if (config.experimental?.athenaStorageBackend) {
6375
+ const storageClient = {
6376
+ ...sdkClient,
6377
+ storage: createStorageModule(gateway, config.experimental.storage)
6378
+ };
6379
+ return storageClient;
6380
+ }
6381
+ return sdkClient;
5411
6382
  }
5412
6383
  var DEFAULT_BACKEND = { type: "athena" };
5413
6384
  function toBackendConfig(b) {