@xylex-group/athena 2.12.1 → 2.14.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 (96) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +1190 -1184
  3. package/bin/athena-js.js +104 -76
  4. package/dist/admin.cjs +45 -0
  5. package/dist/admin.cjs.map +1 -0
  6. package/dist/admin.d.cts +64 -0
  7. package/dist/admin.d.ts +64 -0
  8. package/dist/admin.js +41 -0
  9. package/dist/admin.js.map +1 -0
  10. package/dist/athena-auth-url-oLux_57a.d.cts +377 -0
  11. package/dist/athena-auth-url-oLux_57a.d.ts +377 -0
  12. package/dist/browser.cjs +580 -96
  13. package/dist/browser.cjs.map +1 -1
  14. package/dist/browser.d.cts +12 -10
  15. package/dist/browser.d.ts +12 -10
  16. package/dist/browser.js +580 -96
  17. package/dist/browser.js.map +1 -1
  18. package/dist/cli/index.cjs +690 -91
  19. package/dist/cli/index.cjs.map +1 -1
  20. package/dist/cli/index.d.cts +14 -5
  21. package/dist/cli/index.d.ts +14 -5
  22. package/dist/cli/index.js +690 -92
  23. package/dist/cli/index.js.map +1 -1
  24. package/dist/{client-CMtx5P4D.d.cts → client-uthENhaf.d.ts} +346 -1488
  25. package/dist/{client-Dre8H24u.d.ts → client-wU2J9yqb.d.cts} +346 -1488
  26. package/dist/cookies.cjs +18 -0
  27. package/dist/cookies.cjs.map +1 -1
  28. package/dist/cookies.d.cts +2 -1
  29. package/dist/cookies.d.ts +2 -1
  30. package/dist/cookies.js +17 -1
  31. package/dist/cookies.js.map +1 -1
  32. package/dist/{index-CVcQCGyG.d.ts → index-CFL9xbFR.d.cts} +2 -0
  33. package/dist/{index-CVcQCGyG.d.cts → index-UKJpunc6.d.ts} +2 -0
  34. package/dist/index.cjs +648 -96
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.cts +13 -10
  37. package/dist/index.d.ts +13 -10
  38. package/dist/index.js +648 -97
  39. package/dist/index.js.map +1 -1
  40. package/dist/{model-form-DfTi8-D1.d.cts → model-form-BE1_Bmdd.d.cts} +2 -2
  41. package/dist/{model-form-CU0mWrF9.d.ts → model-form-DcH3R7WD.d.ts} +2 -2
  42. package/dist/{module-DBGmbIuh.d.ts → module-Ca3_OQqR.d.ts} +12 -9
  43. package/dist/{module-GoijrBXV.d.cts → module-DFGZXCtt.d.cts} +12 -9
  44. package/dist/next/client.cjs +992 -89
  45. package/dist/next/client.cjs.map +1 -1
  46. package/dist/next/client.d.cts +7 -4
  47. package/dist/next/client.d.ts +7 -4
  48. package/dist/next/client.js +970 -90
  49. package/dist/next/client.js.map +1 -1
  50. package/dist/next/server.cjs +832 -89
  51. package/dist/next/server.cjs.map +1 -1
  52. package/dist/next/server.d.cts +81 -5
  53. package/dist/next/server.d.ts +81 -5
  54. package/dist/next/server.js +820 -90
  55. package/dist/next/server.js.map +1 -1
  56. package/dist/organization.cjs +72 -0
  57. package/dist/organization.cjs.map +1 -0
  58. package/dist/organization.d.cts +43 -0
  59. package/dist/organization.d.ts +43 -0
  60. package/dist/organization.js +70 -0
  61. package/dist/organization.js.map +1 -0
  62. package/dist/payload-BbSCmILD.d.ts +219 -0
  63. package/dist/payload-zXIwKTQf.d.cts +219 -0
  64. package/dist/{pipeline-c7Gdm0qv.d.cts → pipeline-CwQoD5G9.d.cts} +1 -1
  65. package/dist/{pipeline-DrjU2vNA.d.ts → pipeline-DqwehoQV.d.ts} +1 -1
  66. package/dist/react.cjs +2 -13
  67. package/dist/react.cjs.map +1 -1
  68. package/dist/react.d.cts +26 -7
  69. package/dist/react.d.ts +26 -7
  70. package/dist/react.js +2 -13
  71. package/dist/react.js.map +1 -1
  72. package/dist/session-cookie-detection-BqOp9mO6.d.cts +46 -0
  73. package/dist/session-cookie-detection-BqOp9mO6.d.ts +46 -0
  74. package/dist/social-providers.cjs +4198 -0
  75. package/dist/social-providers.cjs.map +1 -0
  76. package/dist/social-providers.d.cts +4948 -0
  77. package/dist/social-providers.d.ts +4948 -0
  78. package/dist/social-providers.js +4126 -0
  79. package/dist/social-providers.js.map +1 -0
  80. package/dist/{types-kPaHUqUa.d.ts → types-6H575ITc.d.cts} +50 -2
  81. package/dist/{types-DRRb0Fd0.d.ts → types-C1swabT5.d.ts} +3 -3
  82. package/dist/{types-Bez4HSbI.d.cts → types-CD6K05JQ.d.ts} +50 -2
  83. package/dist/{types-BRUHGXo2.d.ts → types-YQUR7wu0.d.cts} +3 -3
  84. package/dist/{types-BRUHGXo2.d.cts → types-YQUR7wu0.d.ts} +3 -3
  85. package/dist/{types-BLizCLd1.d.cts → types-dHnjluBC.d.cts} +3 -3
  86. package/dist/types-eAKAh71s.d.cts +1476 -0
  87. package/dist/types-eAKAh71s.d.ts +1476 -0
  88. package/dist/utils.cjs +438 -15
  89. package/dist/utils.cjs.map +1 -1
  90. package/dist/utils.d.cts +76 -11
  91. package/dist/utils.d.ts +76 -11
  92. package/dist/utils.js +390 -16
  93. package/dist/utils.js.map +1 -1
  94. package/package.json +29 -1
  95. package/dist/shared-DZSGAmXs.d.cts +0 -35
  96. package/dist/shared-MMnVBBfy.d.ts +0 -35
package/dist/index.js CHANGED
@@ -804,7 +804,7 @@ var getCookieCache = async (request2, config) => {
804
804
 
805
805
  // src/utils/athena-request-headers.ts
806
806
  var NO_CACHE_HEADER_VALUE = "no-cache";
807
- var API_KEY_HEADER_CANDIDATES = ["X-Api-Key", "x-api-key", "apikey"];
807
+ var API_KEY_HEADER_CANDIDATES = ["X-Athena-Key", "x-athena-key", "X-Api-Key", "x-api-key", "apikey"];
808
808
  var ATHENA_KEY_HEADER_CANDIDATES = ["X-Athena-Key", "x-athena-key"];
809
809
  var SESSION_TOKEN_HEADER_CANDIDATES = ["X-Athena-Auth-Session-Token"];
810
810
  var BEARER_MIRROR_HEADER_CANDIDATES = ["X-Athena-Auth-Bearer-Token"];
@@ -906,17 +906,6 @@ function buildServiceRequestHeaders(profile, sdkHeaderValue, config, options, ex
906
906
  });
907
907
  }
908
908
  function applyAthenaApiKeyHeaders(headers, apiKey, athenaKey) {
909
- if (apiKey) {
910
- if (!hasHeaderIgnoreCase(headers, "apikey")) {
911
- headers.apikey = apiKey;
912
- }
913
- if (!Object.hasOwn(headers, "x-api-key")) {
914
- headers["x-api-key"] = apiKey;
915
- }
916
- if (!Object.hasOwn(headers, "X-Api-Key")) {
917
- headers["X-Api-Key"] = apiKey;
918
- }
919
- }
920
909
  const resolvedAthenaKey = normalizeHeaderValue(athenaKey) ?? normalizeHeaderValue(apiKey);
921
910
  if (resolvedAthenaKey && !hasHeaderIgnoreCase(headers, "X-Athena-Key")) {
922
911
  headers["X-Athena-Key"] = resolvedAthenaKey;
@@ -1042,7 +1031,7 @@ function buildAthenaRequestHeaders(input) {
1042
1031
 
1043
1032
  // package.json
1044
1033
  var package_default = {
1045
- version: "2.12.1"
1034
+ version: "2.14.0"
1046
1035
  };
1047
1036
 
1048
1037
  // src/sdk-version.ts
@@ -3745,39 +3734,224 @@ async function withRetry(config, fn) {
3745
3734
  throw new Error("withRetry reached an unexpected state");
3746
3735
  }
3747
3736
 
3748
- // src/db/module.ts
3749
- function createDbModule(input) {
3750
- const db = {
3751
- from: input.from,
3752
- select(table2, first, second) {
3753
- if (first && typeof first === "object" && !Array.isArray(first)) {
3754
- return input.from(table2).select(void 0, first);
3737
+ // src/storage/direct-upload.ts
3738
+ var SERVICE = "s3";
3739
+ var TERMINATOR = "aws4_request";
3740
+ async function putDirectStorageUploadBody(config, bucket, storageKey, body, uploadHeaders, signal, onProgress) {
3741
+ if (config.bucket && bucket && config.bucket !== bucket) {
3742
+ throw new Error(
3743
+ `athena.storage.file.upload direct mode bucket mismatch: configured ${config.bucket} but Athena returned ${bucket}`
3744
+ );
3745
+ }
3746
+ const target = createDirectUploadTarget(config, bucket, storageKey);
3747
+ const bytes = await bodyToArrayBuffer(body);
3748
+ const payloadHash = await sha256Hex(bytes);
3749
+ const headers = new Headers(uploadHeaders);
3750
+ if (isBlobBody(body) && body.type && !headers.has("Content-Type")) {
3751
+ headers.set("Content-Type", body.type);
3752
+ }
3753
+ const signed = await signDirectUploadRequest(config, target, headers, payloadHash);
3754
+ if (typeof XMLHttpRequest !== "undefined") {
3755
+ return putWithXhr(target.toString(), signed, body, signal, onProgress);
3756
+ }
3757
+ onProgress({ loaded: 0 });
3758
+ const response = await fetch(target, {
3759
+ method: "PUT",
3760
+ headers: signed.requestHeaders,
3761
+ body,
3762
+ signal
3763
+ });
3764
+ if (!response.ok) {
3765
+ throw new Error(`athena.storage.file.upload failed with status ${response.status}`);
3766
+ }
3767
+ onProgress({ loaded: bytes.byteLength });
3768
+ return response;
3769
+ }
3770
+ function createDirectUploadTarget(config, bucket, storageKey) {
3771
+ const resolvedBucket = config.bucket ?? bucket;
3772
+ if (!resolvedBucket?.trim()) {
3773
+ throw new Error(
3774
+ "athena.storage.file.upload direct mode requires a bucket in experimental.directStorageUpload or the server upload response"
3775
+ );
3776
+ }
3777
+ if (!storageKey.trim()) {
3778
+ throw new Error("athena.storage.file.upload direct mode requires a storage key");
3779
+ }
3780
+ let endpoint;
3781
+ try {
3782
+ endpoint = new URL(config.endpoint);
3783
+ } catch (error) {
3784
+ throw new Error(
3785
+ `athena.storage.file.upload direct mode received an invalid endpoint: ${error instanceof Error ? error.message : String(error)}`
3786
+ );
3787
+ }
3788
+ if (endpoint.search || endpoint.hash) {
3789
+ throw new Error("athena.storage.file.upload direct mode endpoint must not contain a query or hash");
3790
+ }
3791
+ const endpointPath = endpoint.pathname.replace(/\/+$/, "");
3792
+ const pathParts = config.forcePathStyle === false ? [endpointPath, storageKey] : [endpointPath, resolvedBucket, storageKey];
3793
+ if (config.forcePathStyle === false) {
3794
+ endpoint.hostname = `${resolvedBucket}.${endpoint.hostname}`;
3795
+ }
3796
+ endpoint.pathname = pathParts.filter(Boolean).flatMap((part) => part.split("/")).map(awsEncode).join("/").replace(/^([^/])/, "/$1");
3797
+ return endpoint;
3798
+ }
3799
+ async function signDirectUploadRequest(config, target, inputHeaders, payloadHash) {
3800
+ const accessKeyId = config.accessKeyId.trim();
3801
+ const secretAccessKey = config.secretAccessKey.trim();
3802
+ if (!accessKeyId || !secretAccessKey) {
3803
+ throw new Error(
3804
+ "athena.storage.file.upload direct mode requires accessKeyId and secretAccessKey"
3805
+ );
3806
+ }
3807
+ const now = /* @__PURE__ */ new Date();
3808
+ const amzDate = formatAmzDate(now);
3809
+ const shortDate = amzDate.slice(0, 8);
3810
+ const region = config.region?.trim() || "auto";
3811
+ const headers = {};
3812
+ inputHeaders.forEach((value, key) => {
3813
+ if (key.toLowerCase() !== "authorization" && key.toLowerCase() !== "host") {
3814
+ headers[key.toLowerCase()] = value.trim().replace(/\s+/g, " ");
3815
+ }
3816
+ });
3817
+ headers["x-amz-content-sha256"] = payloadHash;
3818
+ headers["x-amz-date"] = amzDate;
3819
+ if (config.sessionToken?.trim()) {
3820
+ headers["x-amz-security-token"] = config.sessionToken.trim();
3821
+ }
3822
+ const canonicalHeaders = Object.keys(headers).sort().map((key) => `${key}:${headers[key]}
3823
+ `).join("");
3824
+ const signedHeaders = Object.keys(headers).sort().join(";");
3825
+ const canonicalRequest = [
3826
+ "PUT",
3827
+ target.pathname,
3828
+ "",
3829
+ `host:${target.host}
3830
+ ${canonicalHeaders}`,
3831
+ `host;${signedHeaders}`,
3832
+ payloadHash
3833
+ ].join("\n");
3834
+ const credentialScope = `${shortDate}/${region}/${SERVICE}/${TERMINATOR}`;
3835
+ const stringToSign = [
3836
+ "AWS4-HMAC-SHA256",
3837
+ amzDate,
3838
+ credentialScope,
3839
+ await sha256Hex(canonicalRequest)
3840
+ ].join("\n");
3841
+ const dateKey = await hmac(`AWS4${secretAccessKey}`, shortDate);
3842
+ const regionKey = await hmac(dateKey, region);
3843
+ const serviceKey = await hmac(regionKey, SERVICE);
3844
+ const signingKey = await hmac(serviceKey, TERMINATOR);
3845
+ const signature = await hmacHex(signingKey, stringToSign);
3846
+ headers.authorization = `AWS4-HMAC-SHA256 Credential=${accessKeyId}/${credentialScope}, SignedHeaders=host;${signedHeaders}, Signature=${signature}`;
3847
+ return { requestHeaders: headers };
3848
+ }
3849
+ async function putWithXhr(url, signed, body, signal, onProgress) {
3850
+ const Xhr = XMLHttpRequest;
3851
+ if (Xhr === void 0) {
3852
+ return Promise.reject(new Error("athena.storage.file.upload direct mode requires XMLHttpRequest in this runtime"));
3853
+ }
3854
+ return new Promise((resolve3, reject) => {
3855
+ const xhr = new Xhr();
3856
+ const abort = () => xhr.abort();
3857
+ xhr.open("PUT", url);
3858
+ Object.entries(signed.requestHeaders).forEach(([key, value]) => xhr.setRequestHeader(key, value));
3859
+ xhr.upload.onprogress = (event) => onProgress({ loaded: event.loaded });
3860
+ xhr.onload = () => {
3861
+ signal?.removeEventListener("abort", abort);
3862
+ if (xhr.status < 200 || xhr.status >= 300) {
3863
+ reject(new Error(`athena.storage.file.upload failed with status ${xhr.status}`));
3864
+ return;
3755
3865
  }
3756
- return input.from(table2).select(first, second);
3757
- },
3758
- insert(table2, values, options) {
3759
- return Array.isArray(values) ? input.from(table2).insert(values, options) : input.from(table2).insert(values, options);
3760
- },
3761
- upsert(table2, values, options) {
3762
- return Array.isArray(values) ? input.from(table2).upsert(values, options) : input.from(table2).upsert(values, options);
3763
- },
3764
- update(table2, values, options) {
3765
- return input.from(table2).update(values, options);
3766
- },
3767
- delete(table2, options) {
3768
- return input.from(table2).delete(options);
3769
- },
3770
- rpc(fn, args, options) {
3771
- return input.rpc(fn, args, options);
3772
- },
3773
- query(query, options) {
3774
- return input.query(query, options);
3866
+ onProgress({ loaded: bodySize(body) });
3867
+ resolve3(new Response(xhr.response, {
3868
+ status: xhr.status,
3869
+ statusText: xhr.statusText,
3870
+ headers: parseXhrHeaders(xhr.getAllResponseHeaders())
3871
+ }));
3872
+ };
3873
+ xhr.onerror = () => {
3874
+ signal?.removeEventListener("abort", abort);
3875
+ reject(new Error("athena.storage.file.upload failed with a network error"));
3876
+ };
3877
+ xhr.onabort = () => {
3878
+ signal?.removeEventListener("abort", abort);
3879
+ reject(new DOMException("Upload aborted", "AbortError"));
3880
+ };
3881
+ if (signal) {
3882
+ if (signal.aborted) {
3883
+ abort();
3884
+ return;
3885
+ }
3886
+ signal.addEventListener("abort", abort, { once: true });
3775
3887
  }
3776
- };
3777
- return db;
3888
+ xhr.send(body);
3889
+ });
3890
+ }
3891
+ function isBlobBody(body) {
3892
+ return typeof Blob !== "undefined" && body instanceof Blob;
3893
+ }
3894
+ async function bodyToArrayBuffer(body) {
3895
+ if (isBlobBody(body)) return body.arrayBuffer();
3896
+ if (body instanceof ArrayBuffer) return body;
3897
+ if (ArrayBuffer.isView(body)) {
3898
+ return body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength);
3899
+ }
3900
+ throw new Error("athena.storage.file.upload direct mode does not support ReadableStream bodies");
3901
+ }
3902
+ function bodySize(body) {
3903
+ if (isBlobBody(body)) return body.size;
3904
+ if (body instanceof ArrayBuffer) return body.byteLength;
3905
+ if (ArrayBuffer.isView(body)) return body.byteLength;
3906
+ return 0;
3907
+ }
3908
+ function awsEncode(value) {
3909
+ return encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
3910
+ }
3911
+ function formatAmzDate(date) {
3912
+ return date.toISOString().replace(/[:-]|\.\d{3}/g, "");
3913
+ }
3914
+ async function sha256Hex(value) {
3915
+ const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value;
3916
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
3917
+ return toHex(new Uint8Array(digest));
3918
+ }
3919
+ async function hmac(key, value) {
3920
+ const keyBytes = typeof key === "string" ? new TextEncoder().encode(key) : key;
3921
+ const cryptoKey = await crypto.subtle.importKey(
3922
+ "raw",
3923
+ keyBytes,
3924
+ { name: "HMAC", hash: "SHA-256" },
3925
+ false,
3926
+ ["sign"]
3927
+ );
3928
+ return crypto.subtle.sign("HMAC", cryptoKey, new TextEncoder().encode(value));
3929
+ }
3930
+ async function hmacHex(key, value) {
3931
+ return toHex(new Uint8Array(await hmac(key, value)));
3932
+ }
3933
+ function toHex(bytes) {
3934
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
3935
+ }
3936
+ function parseXhrHeaders(rawHeaders) {
3937
+ const headers = new Headers();
3938
+ rawHeaders.trim().split(/[\r\n]+/).forEach((line) => {
3939
+ const separator = line.indexOf(":");
3940
+ if (separator > 0) {
3941
+ headers.set(line.slice(0, separator).trim(), line.slice(separator + 1).trim());
3942
+ }
3943
+ });
3944
+ return headers;
3778
3945
  }
3779
3946
 
3780
3947
  // src/storage/file.ts
3948
+ function mergeUploadHeaders(serverHeaders, inputHeaders) {
3949
+ const headers = { ...serverHeaders };
3950
+ new Headers(inputHeaders).forEach((value, key) => {
3951
+ headers[key] = value;
3952
+ });
3953
+ return headers;
3954
+ }
3781
3955
  function createStorageFileModule(base, config = {}) {
3782
3956
  const upload = async (input, options) => {
3783
3957
  const sources = normalizeUploadSources(input);
@@ -3813,16 +3987,25 @@ function createStorageFileModule(base, config = {}) {
3813
3987
  for (let index = 0; index < uploadRequests.length; index += 1) {
3814
3988
  const request2 = uploadRequests[index];
3815
3989
  const uploadUrl = uploadUrls[index];
3816
- const response = await putUploadBody(
3990
+ const aggregateProgress = (progress) => {
3991
+ aggregateLoaded[index] = progress.loaded;
3992
+ input.onProgress?.(createProgressSnapshot("uploading", sources, index, progress.loaded, sum(aggregateLoaded)));
3993
+ };
3994
+ const response = config.directUpload ? await putDirectStorageUploadBody(
3995
+ config.directUpload,
3996
+ uploadUrl.upload.bucket,
3997
+ uploadUrl.upload.storage_key,
3998
+ request2.source.source,
3999
+ mergeUploadHeaders(uploadUrl.upload.headers ?? {}, input.uploadHeaders),
4000
+ options?.signal,
4001
+ aggregateProgress
4002
+ ) : await putUploadBody(
3817
4003
  uploadUrl.upload.url,
3818
4004
  uploadUrl.upload.headers ?? {},
3819
4005
  request2.source,
3820
4006
  input,
3821
4007
  options,
3822
- (progress) => {
3823
- aggregateLoaded[index] = progress.loaded;
3824
- input.onProgress?.(createProgressSnapshot("uploading", sources, index, progress.loaded, sum(aggregateLoaded)));
3825
- }
4008
+ aggregateProgress
3826
4009
  );
3827
4010
  uploaded.push({
3828
4011
  file: uploadUrl.file,
@@ -3973,7 +4156,7 @@ function putUploadBodyWithXhr(url, source, headers, options, onProgress) {
3973
4156
  resolve3(new Response(xhr.response, {
3974
4157
  status: xhr.status,
3975
4158
  statusText: xhr.statusText,
3976
- headers: parseXhrHeaders(xhr.getAllResponseHeaders())
4159
+ headers: parseXhrHeaders2(xhr.getAllResponseHeaders())
3977
4160
  }));
3978
4161
  };
3979
4162
  xhr.onerror = () => {
@@ -4111,7 +4294,7 @@ function createProgressSnapshot(phase, sources, fileIndex, loaded, aggregateLoad
4111
4294
  function sum(values) {
4112
4295
  return values.reduce((total, value) => total + value, 0);
4113
4296
  }
4114
- function parseXhrHeaders(raw) {
4297
+ function parseXhrHeaders2(raw) {
4115
4298
  const headers = new Headers();
4116
4299
  for (const line of raw.trim().split(/[\r\n]+/)) {
4117
4300
  const index = line.indexOf(":");
@@ -4128,6 +4311,230 @@ function isRecord5(value) {
4128
4311
  return Boolean(value) && typeof value === "object";
4129
4312
  }
4130
4313
 
4314
+ // src/storage/backup.ts
4315
+ function backupError(message, status, endpoint, method, cause, raw) {
4316
+ const error = new Error(message);
4317
+ error.name = "AthenaStorageError";
4318
+ error.code = status === 0 ? "NETWORK_ERROR" : "HTTP_ERROR";
4319
+ error.status = status;
4320
+ error.endpoint = endpoint;
4321
+ error.method = method;
4322
+ error.cause = cause;
4323
+ error.raw = raw;
4324
+ throw error;
4325
+ }
4326
+ function isRecord6(value) {
4327
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
4328
+ }
4329
+ function asPath(path) {
4330
+ return path;
4331
+ }
4332
+ function appendQuery(path, query) {
4333
+ if (!query) return path;
4334
+ const params = new URLSearchParams();
4335
+ for (const [key, value] of Object.entries(query)) {
4336
+ if (value === void 0 || value === null || value === "") continue;
4337
+ params.set(key, String(value));
4338
+ }
4339
+ const text = params.toString();
4340
+ return text ? `${path}?${text}` : path;
4341
+ }
4342
+ function unwrapAthenaData(payload) {
4343
+ if (isRecord6(payload) && "data" in payload) {
4344
+ return payload.data;
4345
+ }
4346
+ return payload;
4347
+ }
4348
+ function requireKey(key) {
4349
+ const trimmed = key.trim();
4350
+ if (!trimmed || trimmed === "undefined" || trimmed === "null") {
4351
+ backupError("Backup object key is required", 400, "/admin/backups/{key}", "DELETE");
4352
+ }
4353
+ return trimmed;
4354
+ }
4355
+ function resolveMessage(payload, fallback) {
4356
+ if (isRecord6(payload)) {
4357
+ const message = payload.message ?? payload.error ?? payload.details;
4358
+ if (typeof message === "string" && message.trim()) return message.trim();
4359
+ }
4360
+ if (typeof payload === "string" && payload.trim()) return payload.trim();
4361
+ return fallback;
4362
+ }
4363
+ async function callBackupEndpoint(gateway, path, method, payload, options, runtime) {
4364
+ const endpoint = asPath(path);
4365
+ const baseUrl = options?.baseUrl ? normalizeAthenaGatewayBaseUrl(options.baseUrl) : gateway.baseUrl;
4366
+ const url = buildAthenaGatewayUrl(baseUrl, endpoint);
4367
+ const headers = gateway.buildHeaders(options);
4368
+ const init = {
4369
+ method,
4370
+ headers,
4371
+ signal: options?.signal
4372
+ };
4373
+ if (payload !== void 0 && method !== "GET") {
4374
+ init.body = JSON.stringify(payload);
4375
+ }
4376
+ let response;
4377
+ try {
4378
+ response = await fetch(url, init);
4379
+ } catch (error) {
4380
+ backupError(
4381
+ error instanceof Error ? error.message : "Backup network error",
4382
+ 0,
4383
+ path,
4384
+ method,
4385
+ error
4386
+ );
4387
+ }
4388
+ const rawText = await response.text();
4389
+ let parsed = null;
4390
+ if (rawText) {
4391
+ try {
4392
+ parsed = JSON.parse(rawText);
4393
+ } catch {
4394
+ parsed = rawText;
4395
+ }
4396
+ }
4397
+ if (!response.ok) {
4398
+ backupError(
4399
+ resolveMessage(parsed, `Backup ${method} ${path} failed (${response.status})`),
4400
+ response.status,
4401
+ path,
4402
+ method,
4403
+ void 0,
4404
+ parsed
4405
+ );
4406
+ }
4407
+ return unwrapAthenaData(parsed);
4408
+ }
4409
+ function createStorageBackupModule(gateway, runtimeOptions) {
4410
+ const resolvedBaseUrl = () => String(gateway.baseUrl ?? "").replace(/\/+$/, "");
4411
+ return {
4412
+ async list(query, options) {
4413
+ const path = appendQuery("/admin/backups", {
4414
+ limit: query?.limit ?? 10,
4415
+ client_name: query?.client_name,
4416
+ cursor: query?.cursor ?? void 0
4417
+ });
4418
+ const data = await callBackupEndpoint(gateway, path, "GET", void 0, options);
4419
+ const backups = (data?.backups ?? []).map((row) => ({
4420
+ ...row,
4421
+ key: row.key ?? row.s3_key
4422
+ }));
4423
+ return {
4424
+ backups,
4425
+ next_cursor: data?.next_cursor ?? null
4426
+ };
4427
+ },
4428
+ async create(input, options) {
4429
+ const data = await callBackupEndpoint(gateway, "/admin/backups", "POST", input, options);
4430
+ return {
4431
+ job_id: Number(data?.job_id ?? 0),
4432
+ client_name: String(data?.client_name ?? input.client_name),
4433
+ status: String(data?.status ?? "pending")
4434
+ };
4435
+ },
4436
+ async restore(key, input, options) {
4437
+ const backupKey = requireKey(key);
4438
+ const path = `/admin/backups/${encodeURIComponent(backupKey)}/restore`;
4439
+ const data = await callBackupEndpoint(gateway, path, "POST", input, options);
4440
+ return {
4441
+ job_id: Number(data?.job_id ?? 0),
4442
+ client_name: String(data?.client_name ?? input.client_name),
4443
+ status: String(data?.status ?? "pending"),
4444
+ key: String(data?.key ?? backupKey)
4445
+ };
4446
+ },
4447
+ async delete(key, options) {
4448
+ const backupKey = requireKey(key);
4449
+ await callBackupEndpoint(
4450
+ gateway,
4451
+ `/admin/backups/${encodeURIComponent(backupKey)}`,
4452
+ "DELETE",
4453
+ void 0,
4454
+ options);
4455
+ },
4456
+ downloadUrl(key, options) {
4457
+ const backupKey = requireKey(key);
4458
+ const base = `${resolvedBaseUrl()}/admin/backups/${encodeURIComponent(backupKey)}/download`;
4459
+ return options?.apiKey ? `${base}?api_key=${encodeURIComponent(options.apiKey)}` : base;
4460
+ },
4461
+ jobs: {
4462
+ async list(query, options) {
4463
+ const path = appendQuery("/admin/backups/jobs", query ?? {});
4464
+ const data = await callBackupEndpoint(gateway, path, "GET", void 0, options);
4465
+ if (Array.isArray(data)) return data;
4466
+ if (isRecord6(data) && Array.isArray(data.jobs)) return data.jobs;
4467
+ return [];
4468
+ },
4469
+ async get(jobId, options) {
4470
+ return callBackupEndpoint(
4471
+ gateway,
4472
+ `/admin/backups/jobs/${encodeURIComponent(String(jobId))}`,
4473
+ "GET",
4474
+ void 0,
4475
+ options);
4476
+ },
4477
+ async cancel(jobId, options) {
4478
+ return callBackupEndpoint(
4479
+ gateway,
4480
+ `/admin/backups/jobs/${encodeURIComponent(String(jobId))}/cancel`,
4481
+ "POST",
4482
+ {},
4483
+ options);
4484
+ },
4485
+ async delete(jobId, options) {
4486
+ await callBackupEndpoint(
4487
+ gateway,
4488
+ `/admin/backups/jobs/${encodeURIComponent(String(jobId))}`,
4489
+ "DELETE",
4490
+ void 0,
4491
+ options);
4492
+ },
4493
+ async openObjectUrl(jobId, options) {
4494
+ const data = await callBackupEndpoint(
4495
+ gateway,
4496
+ `/admin/backups/jobs/${encodeURIComponent(String(jobId))}/s3-open`,
4497
+ "GET",
4498
+ void 0,
4499
+ options);
4500
+ return String(data?.url ?? "");
4501
+ }
4502
+ },
4503
+ schedules: {
4504
+ async list(options) {
4505
+ const data = await callBackupEndpoint(gateway, "/admin/backups/schedules", "GET", void 0, options);
4506
+ if (Array.isArray(data)) return data;
4507
+ if (isRecord6(data) && Array.isArray(data.schedules)) return data.schedules;
4508
+ return [];
4509
+ },
4510
+ async create(input, options) {
4511
+ return callBackupEndpoint(
4512
+ gateway,
4513
+ "/admin/backups/schedules",
4514
+ "POST",
4515
+ input,
4516
+ options);
4517
+ },
4518
+ async update(id, input, options) {
4519
+ return callBackupEndpoint(
4520
+ gateway,
4521
+ `/admin/backups/schedules/${encodeURIComponent(String(id))}`,
4522
+ "PATCH",
4523
+ input,
4524
+ options);
4525
+ },
4526
+ async delete(id, options) {
4527
+ await callBackupEndpoint(
4528
+ gateway,
4529
+ `/admin/backups/schedules/${encodeURIComponent(String(id))}`,
4530
+ "DELETE",
4531
+ void 0,
4532
+ options);
4533
+ }
4534
+ }
4535
+ };
4536
+ }
4537
+
4131
4538
  // src/storage/module.ts
4132
4539
  var storageSdkManifest = {
4133
4540
  namespace: "storage",
@@ -4176,6 +4583,53 @@ var storageSdkManifest = {
4176
4583
  responseEnvelope: "raw",
4177
4584
  responseType: "{ data: S3CredentialListItem[] }"
4178
4585
  },
4586
+ {
4587
+ name: "backup.list",
4588
+ method: "GET",
4589
+ path: "/admin/backups",
4590
+ responseEnvelope: "athena",
4591
+ responseType: "StorageBackupListPage",
4592
+ note: "Admin backup archives on server S3/R2 profile"
4593
+ },
4594
+ {
4595
+ name: "backup.create",
4596
+ method: "POST",
4597
+ path: "/admin/backups",
4598
+ requestType: "StorageBackupCreateRequest",
4599
+ responseEnvelope: "athena",
4600
+ responseType: "StorageBackupQueuedJob"
4601
+ },
4602
+ {
4603
+ name: "backup.restore",
4604
+ method: "POST",
4605
+ path: "/admin/backups/{key}/restore",
4606
+ pathParams: ["key"],
4607
+ requestType: "StorageBackupRestoreRequest",
4608
+ responseEnvelope: "athena",
4609
+ responseType: "StorageBackupQueuedJob"
4610
+ },
4611
+ {
4612
+ name: "backup.delete",
4613
+ method: "DELETE",
4614
+ path: "/admin/backups/{key}",
4615
+ pathParams: ["key"],
4616
+ responseEnvelope: "athena",
4617
+ responseType: "void"
4618
+ },
4619
+ {
4620
+ name: "backup.jobs.list",
4621
+ method: "GET",
4622
+ path: "/admin/backups/jobs",
4623
+ responseEnvelope: "athena",
4624
+ responseType: "StorageBackupJob[]"
4625
+ },
4626
+ {
4627
+ name: "backup.schedules.list",
4628
+ method: "GET",
4629
+ path: "/admin/backups/schedules",
4630
+ responseEnvelope: "athena",
4631
+ responseType: "StorageBackupSchedule[]"
4632
+ },
4179
4633
  {
4180
4634
  name: "createStorageUploadUrl",
4181
4635
  method: "POST",
@@ -4831,7 +5285,7 @@ var AthenaStorageError = class extends Error {
4831
5285
  };
4832
5286
  }
4833
5287
  };
4834
- function isRecord6(value) {
5288
+ function isRecord7(value) {
4835
5289
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
4836
5290
  }
4837
5291
  function causeToString(cause) {
@@ -4929,7 +5383,7 @@ function parseResponseBody3(rawText, contentType) {
4929
5383
  return { parsed: rawText, parseFailed: true };
4930
5384
  }
4931
5385
  }
4932
- function appendQuery(path, query) {
5386
+ function appendQuery2(path, query) {
4933
5387
  if (!query) return path;
4934
5388
  const params = new URLSearchParams();
4935
5389
  for (const [key, value] of Object.entries(query)) {
@@ -4955,7 +5409,7 @@ function withPathParam(path, name, value) {
4955
5409
  return path.replace(`{${name}}`, encodeURIComponent(value));
4956
5410
  }
4957
5411
  function resolveErrorMessage3(payload, fallback) {
4958
- if (isRecord6(payload)) {
5412
+ if (isRecord7(payload)) {
4959
5413
  const message = payload.message ?? payload.error ?? payload.details;
4960
5414
  if (typeof message === "string" && message.trim()) {
4961
5415
  return message.trim();
@@ -4967,12 +5421,12 @@ function resolveErrorMessage3(payload, fallback) {
4967
5421
  return fallback;
4968
5422
  }
4969
5423
  function resolveErrorHint2(payload) {
4970
- if (!isRecord6(payload)) return void 0;
5424
+ if (!isRecord7(payload)) return void 0;
4971
5425
  const hint = payload.hint ?? payload.suggestion;
4972
5426
  return typeof hint === "string" && hint.trim() ? hint.trim() : void 0;
4973
5427
  }
4974
5428
  function resolveErrorCause(payload) {
4975
- if (!isRecord6(payload)) return void 0;
5429
+ if (!isRecord7(payload)) return void 0;
4976
5430
  const cause = payload.cause ?? payload.reason;
4977
5431
  return typeof cause === "string" && cause.trim() ? cause.trim() : void 0;
4978
5432
  }
@@ -5091,7 +5545,7 @@ async function callStorageEndpoint(gateway, endpoint, method, envelope, payload,
5091
5545
  );
5092
5546
  }
5093
5547
  if (envelope === "athena") {
5094
- if (!isRecord6(parsedBody.parsed) || !("data" in parsedBody.parsed)) {
5548
+ if (!isRecord7(parsedBody.parsed) || !("data" in parsedBody.parsed)) {
5095
5549
  return rejectStorageError(
5096
5550
  {
5097
5551
  code: "INVALID_ATHENA_ENVELOPE",
@@ -5199,7 +5653,7 @@ async function callStorageBinaryEndpoint(gateway, endpoint, method, options, run
5199
5653
  runtimeOptions
5200
5654
  );
5201
5655
  }
5202
- function isBlobBody(body) {
5656
+ function isBlobBody2(body) {
5203
5657
  return typeof Blob !== "undefined" && body instanceof Blob;
5204
5658
  }
5205
5659
  function isReadableStreamBody(body) {
@@ -5208,7 +5662,7 @@ function isReadableStreamBody(body) {
5208
5662
  async function putPresignedUploadBody(uploadUrl, uploadHeaders, body, options) {
5209
5663
  const headers = new Headers(uploadHeaders);
5210
5664
  Object.entries(options?.headers ?? {}).forEach(([key, value]) => headers.set(key, value));
5211
- if (!headers.has("Content-Type") && isBlobBody(body) && body.type) {
5665
+ if (!headers.has("Content-Type") && isBlobBody2(body) && body.type) {
5212
5666
  headers.set("Content-Type", body.type);
5213
5667
  }
5214
5668
  const init = {
@@ -5303,7 +5757,7 @@ async function callStorageUploadBinaryEndpoint(gateway, endpoint, body, options,
5303
5757
  }
5304
5758
  delete headers["Content-Type"];
5305
5759
  delete headers["content-type"];
5306
- if (isBlobBody(body) && body.type) {
5760
+ if (isBlobBody2(body) && body.type) {
5307
5761
  headers["Content-Type"] = body.type;
5308
5762
  }
5309
5763
  const requestInit = {
@@ -5388,7 +5842,7 @@ async function callStorageUploadBinaryEndpoint(gateway, endpoint, body, options,
5388
5842
  runtimeOptions
5389
5843
  );
5390
5844
  }
5391
- if (!isRecord6(parsedBody.parsed) || !("data" in parsedBody.parsed)) {
5845
+ if (!isRecord7(parsedBody.parsed) || !("data" in parsedBody.parsed)) {
5392
5846
  return rejectStorageError(
5393
5847
  {
5394
5848
  code: "INVALID_ATHENA_ENVELOPE",
@@ -5460,14 +5914,14 @@ function createStorageModule(gateway, runtimeOptions) {
5460
5914
  return callAthena2(withPathParam("/storage/files/{file_id}", "file_id", fileId), "GET", void 0, options);
5461
5915
  },
5462
5916
  getStorageFileUrl(fileId, query, options) {
5463
- const path = appendQuery(
5917
+ const path = appendQuery2(
5464
5918
  withPathParam("/storage/files/{file_id}/url", "file_id", fileId),
5465
5919
  query
5466
5920
  );
5467
5921
  return callAthena2(path, "GET", void 0, options);
5468
5922
  },
5469
5923
  getStorageFileProxy(fileId, query, options) {
5470
- const path = appendQuery(
5924
+ const path = appendQuery2(
5471
5925
  withPathParam("/storage/files/{file_id}/proxy", "file_id", fileId),
5472
5926
  query
5473
5927
  );
@@ -5491,7 +5945,7 @@ function createStorageModule(gateway, runtimeOptions) {
5491
5945
  };
5492
5946
  const fileFacade = createStorageFileModule(base, runtimeOptions);
5493
5947
  const fileUpload = ((input, options) => {
5494
- if (isRecord6(input) && "files" in input) {
5948
+ if (isRecord7(input) && "files" in input) {
5495
5949
  return fileFacade.upload(input, options);
5496
5950
  }
5497
5951
  return base.createStorageUploadUrl(
@@ -5553,7 +6007,7 @@ function createStorageModule(gateway, runtimeOptions) {
5553
6007
  return callAthena2(withPathParam("/storage/files/{file_id}/public-url", "file_id", fileId), "GET", void 0, options);
5554
6008
  },
5555
6009
  proxyUrl(fileId, query, options) {
5556
- const path = appendQuery(
6010
+ const path = appendQuery2(
5557
6011
  withPathParam("/storage/files/{file_id}/proxy-url", "file_id", fileId),
5558
6012
  query
5559
6013
  );
@@ -5591,7 +6045,7 @@ function createStorageModule(gateway, runtimeOptions) {
5591
6045
  },
5592
6046
  retention: {
5593
6047
  get(fileId, query, options) {
5594
- const path = appendQuery(
6048
+ const path = appendQuery2(
5595
6049
  withPathParam("/storage/files/{file_id}/retention", "file_id", fileId),
5596
6050
  query
5597
6051
  );
@@ -5793,6 +6247,7 @@ function createStorageModule(gateway, runtimeOptions) {
5793
6247
  return callAthena2("/storage/audit/list", "POST", input, options);
5794
6248
  }
5795
6249
  };
6250
+ const backup = createStorageBackupModule(gateway);
5796
6251
  return {
5797
6252
  ...base,
5798
6253
  credentials,
@@ -5804,6 +6259,7 @@ function createStorageModule(gateway, runtimeOptions) {
5804
6259
  bucket,
5805
6260
  multipart,
5806
6261
  audit,
6262
+ backup,
5807
6263
  delete: file.delete
5808
6264
  };
5809
6265
  }
@@ -5853,7 +6309,7 @@ function normalizeWsUrl(value, label) {
5853
6309
  parsed.pathname = parsed.pathname.replace(/\/+$/, "");
5854
6310
  return parsed.toString().replace(/\/$/, "");
5855
6311
  }
5856
- function isRecord7(value) {
6312
+ function isRecord8(value) {
5857
6313
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
5858
6314
  }
5859
6315
  function parseResponseBody4(rawText, contentType) {
@@ -5875,7 +6331,7 @@ function resolveRequestId3(headers) {
5875
6331
  return headers.get("x-request-id") ?? headers.get("x-correlation-id") ?? headers.get("x-athena-request-id") ?? void 0;
5876
6332
  }
5877
6333
  function resolveErrorMessage4(payload, fallback) {
5878
- if (isRecord7(payload)) {
6334
+ if (isRecord8(payload)) {
5879
6335
  for (const candidate of [payload.error, payload.message, payload.details]) {
5880
6336
  if (typeof candidate === "string" && candidate.trim().length > 0) {
5881
6337
  return candidate.trim();
@@ -6522,7 +6978,7 @@ var BOOLEAN_SAFE_OPERATORS = /* @__PURE__ */ new Set([
6522
6978
  "ilike",
6523
6979
  "is"
6524
6980
  ]);
6525
- function isRecord8(value) {
6981
+ function isRecord9(value) {
6526
6982
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6527
6983
  }
6528
6984
  function isUuidString(value) {
@@ -6535,7 +6991,7 @@ function shouldUseUuidTextComparison(column, value) {
6535
6991
  return typeof value === "string" && isUuidString(value) && isUuidIdentifierColumn(column);
6536
6992
  }
6537
6993
  function isRelationSelectNode(value) {
6538
- return isRecord8(value) && isRecord8(value.select);
6994
+ return isRecord9(value) && isRecord9(value.select);
6539
6995
  }
6540
6996
  function normalizeIdentifier(value, label) {
6541
6997
  const normalized = value.trim();
@@ -6591,7 +7047,7 @@ function compileRelationToken(key, node) {
6591
7047
  return `${prefix}${relationToken}(${nested})`;
6592
7048
  }
6593
7049
  function compileSelectShape(select) {
6594
- if (!isRecord8(select)) {
7050
+ if (!isRecord9(select)) {
6595
7051
  throw new Error("findMany select must be an object");
6596
7052
  }
6597
7053
  const tokens = [];
@@ -6615,7 +7071,7 @@ function compileSelectShape(select) {
6615
7071
  return tokens.join(",");
6616
7072
  }
6617
7073
  function selectShapeUsesRelationSchema(select) {
6618
- if (!isRecord8(select)) {
7074
+ if (!isRecord9(select)) {
6619
7075
  return false;
6620
7076
  }
6621
7077
  for (const rawValue of Object.values(select)) {
@@ -6633,7 +7089,7 @@ function selectShapeUsesRelationSchema(select) {
6633
7089
  }
6634
7090
  function compileColumnWhere(column, input) {
6635
7091
  const normalizedColumn = normalizeIdentifier(column, "where column");
6636
- if (!isRecord8(input)) {
7092
+ if (!isRecord9(input)) {
6637
7093
  return [buildGatewayCondition("eq", normalizedColumn, input)];
6638
7094
  }
6639
7095
  const conditions = [];
@@ -6661,7 +7117,7 @@ function compileColumnWhere(column, input) {
6661
7117
  return conditions;
6662
7118
  }
6663
7119
  function compileBooleanExpressionTerms(clause, label) {
6664
- if (!isRecord8(clause)) {
7120
+ if (!isRecord9(clause)) {
6665
7121
  throw new Error(`findMany where.${label} clauses must be objects`);
6666
7122
  }
6667
7123
  const entries = Object.entries(clause).filter(([, value]) => value !== void 0);
@@ -6670,7 +7126,7 @@ function compileBooleanExpressionTerms(clause, label) {
6670
7126
  }
6671
7127
  const [rawColumn, rawValue] = entries[0];
6672
7128
  const column = normalizeIdentifier(rawColumn, `where.${label} column`);
6673
- if (!isRecord8(rawValue)) {
7129
+ if (!isRecord9(rawValue)) {
6674
7130
  return [`${column}.eq.${stringifyFilterValue(rawValue)}`];
6675
7131
  }
6676
7132
  const operatorEntries = Object.entries(rawValue).filter(([, value]) => value !== void 0);
@@ -6694,7 +7150,7 @@ function compileWhere(where) {
6694
7150
  if (where === void 0) {
6695
7151
  return void 0;
6696
7152
  }
6697
- if (!isRecord8(where)) {
7153
+ if (!isRecord9(where)) {
6698
7154
  throw new Error("findMany where must be an object");
6699
7155
  }
6700
7156
  const conditions = [];
@@ -6744,7 +7200,7 @@ function compileOrderBy(orderBy) {
6744
7200
  if (orderBy === void 0) {
6745
7201
  return void 0;
6746
7202
  }
6747
- if (!isRecord8(orderBy)) {
7203
+ if (!isRecord9(orderBy)) {
6748
7204
  throw new Error("findMany orderBy must be an object");
6749
7205
  }
6750
7206
  if ("column" in orderBy) {
@@ -6919,11 +7375,11 @@ function toFindManyAstOrder(order) {
6919
7375
  ascending: order.direction !== "descending"
6920
7376
  };
6921
7377
  }
6922
- function isRecord9(value) {
7378
+ function isRecord10(value) {
6923
7379
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6924
7380
  }
6925
7381
  function normalizeFindManyAstColumnPredicate(value) {
6926
- if (!isRecord9(value)) {
7382
+ if (!isRecord10(value)) {
6927
7383
  return {
6928
7384
  eq: value
6929
7385
  };
@@ -6947,7 +7403,7 @@ function normalizeFindManyAstBooleanOperand(clause) {
6947
7403
  return normalized;
6948
7404
  }
6949
7405
  function normalizeFindManyAstWhere(where) {
6950
- if (!where || !isRecord9(where)) {
7406
+ if (!where || !isRecord10(where)) {
6951
7407
  return where;
6952
7408
  }
6953
7409
  const normalized = {};
@@ -6961,7 +7417,7 @@ function normalizeFindManyAstWhere(where) {
6961
7417
  );
6962
7418
  continue;
6963
7419
  }
6964
- if (key === "not" && isRecord9(value)) {
7420
+ if (key === "not" && isRecord10(value)) {
6965
7421
  normalized.not = normalizeFindManyAstBooleanOperand(
6966
7422
  value
6967
7423
  );
@@ -6972,7 +7428,7 @@ function normalizeFindManyAstWhere(where) {
6972
7428
  return normalized;
6973
7429
  }
6974
7430
  function predicateRequiresUuidQueryFallback(column, value) {
6975
- if (!isRecord9(value)) {
7431
+ if (!isRecord10(value)) {
6976
7432
  return shouldUseUuidTextComparison(column, value);
6977
7433
  }
6978
7434
  const eqValue = value.eq;
@@ -6990,7 +7446,7 @@ function booleanOperandRequiresUuidQueryFallback(clause) {
6990
7446
  return false;
6991
7447
  }
6992
7448
  function findManyAstWhereRequiresLegacyTransport(where) {
6993
- if (!where || !isRecord9(where)) {
7449
+ if (!where || !isRecord10(where)) {
6994
7450
  return false;
6995
7451
  }
6996
7452
  for (const [key, value] of Object.entries(where)) {
@@ -7005,7 +7461,7 @@ function findManyAstWhereRequiresLegacyTransport(where) {
7005
7461
  }
7006
7462
  continue;
7007
7463
  }
7008
- if (key === "not" && isRecord9(value)) {
7464
+ if (key === "not" && isRecord10(value)) {
7009
7465
  if (booleanOperandRequiresUuidQueryFallback(value)) {
7010
7466
  return true;
7011
7467
  }
@@ -7631,7 +8087,7 @@ async function executeExperimentalRead(experimental, runner) {
7631
8087
  throw error;
7632
8088
  }
7633
8089
  }
7634
- function isRecord10(value) {
8090
+ function isRecord11(value) {
7635
8091
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
7636
8092
  }
7637
8093
  function firstNonEmptyString2(...values) {
@@ -7643,8 +8099,8 @@ function firstNonEmptyString2(...values) {
7643
8099
  return void 0;
7644
8100
  }
7645
8101
  function resolveStructuredErrorPayload2(raw) {
7646
- if (!isRecord10(raw)) return null;
7647
- return isRecord10(raw.error) ? raw.error : raw;
8102
+ if (!isRecord11(raw)) return null;
8103
+ return isRecord11(raw.error) ? raw.error : raw;
7648
8104
  }
7649
8105
  function resolveStructuredErrorDetails(payload, message) {
7650
8106
  if (!payload || !("details" in payload)) {
@@ -7660,7 +8116,7 @@ function resolveStructuredErrorDetails(payload, message) {
7660
8116
  return details;
7661
8117
  }
7662
8118
  function createResultError(response, result, normalized) {
7663
- const rawRecord = isRecord10(response.raw) ? response.raw : null;
8119
+ const rawRecord = isRecord11(response.raw) ? response.raw : null;
7664
8120
  const payload = resolveStructuredErrorPayload2(response.raw);
7665
8121
  const message = firstNonEmptyString2(
7666
8122
  response.error,
@@ -9408,7 +9864,30 @@ function createClientFromConfig(config, sourceConfig) {
9408
9864
  config.experimental,
9409
9865
  queryTracer
9410
9866
  );
9411
- const db = createDbModule({ from, rpc, query });
9867
+ const untypedDbFrom = from;
9868
+ const db = {
9869
+ from,
9870
+ select(table2, first, second) {
9871
+ if (first && typeof first === "object" && !Array.isArray(first)) {
9872
+ return untypedDbFrom(table2).select(void 0, first);
9873
+ }
9874
+ return untypedDbFrom(table2).select(first, second);
9875
+ },
9876
+ insert(table2, values, options) {
9877
+ return Array.isArray(values) ? untypedDbFrom(table2).insert(values, options) : untypedDbFrom(table2).insert(values, options);
9878
+ },
9879
+ upsert(table2, values, options) {
9880
+ return Array.isArray(values) ? untypedDbFrom(table2).upsert(values, options) : untypedDbFrom(table2).upsert(values, options);
9881
+ },
9882
+ update(table2, values, options) {
9883
+ return untypedDbFrom(table2).update(values, options);
9884
+ },
9885
+ delete(table2, options) {
9886
+ return untypedDbFrom(table2).delete(options);
9887
+ },
9888
+ rpc,
9889
+ query
9890
+ };
9412
9891
  const chat = createChatModule({
9413
9892
  baseUrl: config.chatUrl,
9414
9893
  apiKey: config.apiKey,
@@ -9546,6 +10025,7 @@ function createClientFromConfig(config, sourceConfig) {
9546
10025
  withOptions: storageWithOptions,
9547
10026
  storage: createStorageModule(gateway, {
9548
10027
  ...config.experimental.storage,
10028
+ ...config.experimental.directStorageUpload ? { directUpload: config.experimental.directStorageUpload } : {},
9549
10029
  ...config.storageUrl ? {
9550
10030
  baseUrl: config.storageUrl,
9551
10031
  stripBasePath: true
@@ -9559,7 +10039,9 @@ function createClientFromConfig(config, sourceConfig) {
9559
10039
  var AthenaClient = class {
9560
10040
  /** Create a fluent builder for a strongly-typed Athena SDK client. */
9561
10041
  static builder() {
9562
- return createAthenaClientBuilder((config) => createClientFromInput(config));
10042
+ return createAthenaClientBuilder(
10043
+ (config) => createClientFromInput(config)
10044
+ );
9563
10045
  }
9564
10046
  static fromEnvironment(options = {}) {
9565
10047
  const env = options.env ?? process.env;
@@ -9590,7 +10072,8 @@ var AthenaClient = class {
9590
10072
  });
9591
10073
  }
9592
10074
  };
9593
- function createClient(configOrUrl, apiKey, options) {
10075
+ function createClient(...args) {
10076
+ const [configOrUrl, apiKey, options] = args;
9594
10077
  if (typeof configOrUrl === "string" || configOrUrl === null || configOrUrl === void 0) {
9595
10078
  return createClientFromInput({
9596
10079
  url: configOrUrl,
@@ -9629,7 +10112,7 @@ function resolveNullishValue(mode) {
9629
10112
  if (mode === "null") return null;
9630
10113
  return "";
9631
10114
  }
9632
- function isRecord11(value) {
10115
+ function isRecord12(value) {
9633
10116
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9634
10117
  }
9635
10118
  function isNullableColumn(model, key) {
@@ -9638,7 +10121,7 @@ function isNullableColumn(model, key) {
9638
10121
  }
9639
10122
  function toModelFormDefaults(model, values, options) {
9640
10123
  const source = values;
9641
- if (!isRecord11(source)) {
10124
+ if (!isRecord12(source)) {
9642
10125
  return {};
9643
10126
  }
9644
10127
  const mode = options?.nullishMode ?? "empty-string";
@@ -10211,7 +10694,8 @@ var TypedAthenaClientImpl = class _TypedAthenaClientImpl {
10211
10694
  fromModel(database, schema, model) {
10212
10695
  const modelDef = this.registryNavigator.resolveModel(database, schema, model);
10213
10696
  const tableName = this.registryNavigator.resolveTableName(schema, model, modelDef);
10214
- return this.baseClient.from(tableName);
10697
+ const from = this.baseClient.from;
10698
+ return from(tableName);
10215
10699
  }
10216
10700
  };
10217
10701
  function createTypedClient(registry, url, apiKey, options) {
@@ -12451,15 +12935,15 @@ function readCookieFromHeaders(headers, name) {
12451
12935
  }
12452
12936
  return parseCookies(cookieHeader).get(name);
12453
12937
  }
12454
- function isRecord12(value) {
12938
+ function isRecord13(value) {
12455
12939
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
12456
12940
  }
12457
12941
  function resolveSessionCandidate(value) {
12458
- if (!isRecord12(value)) {
12942
+ if (!isRecord13(value)) {
12459
12943
  return null;
12460
12944
  }
12461
- const session = isRecord12(value.session) ? value.session : void 0;
12462
- const user = isRecord12(value.user) ? value.user : void 0;
12945
+ const session = isRecord13(value.session) ? value.session : void 0;
12946
+ const user = isRecord13(value.user) ? value.user : void 0;
12463
12947
  if (session && typeof session.token === "string" && session.token.length > 0 && user) {
12464
12948
  return {
12465
12949
  session,
@@ -12469,7 +12953,7 @@ function resolveSessionCandidate(value) {
12469
12953
  return null;
12470
12954
  }
12471
12955
  function inferSessionPair(returned) {
12472
- return resolveSessionCandidate(returned) ?? (isRecord12(returned) ? resolveSessionCandidate(returned.data) : null) ?? (isRecord12(returned) ? resolveSessionCandidate(returned.session) : null);
12956
+ return resolveSessionCandidate(returned) ?? (isRecord13(returned) ? resolveSessionCandidate(returned.data) : null) ?? (isRecord13(returned) ? resolveSessionCandidate(returned.session) : null);
12473
12957
  }
12474
12958
  function resolveResponseHeaders(ctx) {
12475
12959
  if (ctx.context.responseHeaders instanceof Headers) {
@@ -12813,6 +13297,73 @@ function athenaAuth(config) {
12813
13297
  return auth;
12814
13298
  }
12815
13299
 
12816
- 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 };
13300
+ // src/organization/ensure-active-organization.ts
13301
+ function normalizeOrganizationId(value) {
13302
+ if (typeof value !== "string") {
13303
+ return null;
13304
+ }
13305
+ const normalized = value.trim();
13306
+ return normalized.length > 0 ? normalized : null;
13307
+ }
13308
+ function defaultSelectOrganizationId(organizations) {
13309
+ for (const organization of organizations) {
13310
+ const id = normalizeOrganizationId(organization.id);
13311
+ if (id) {
13312
+ return id;
13313
+ }
13314
+ }
13315
+ return null;
13316
+ }
13317
+ async function ensureActiveOrganization(options) {
13318
+ const currentActiveOrganizationId = normalizeOrganizationId(
13319
+ options.session?.session?.activeOrganizationId
13320
+ );
13321
+ if (currentActiveOrganizationId) {
13322
+ return {
13323
+ activeOrganizationId: currentActiveOrganizationId,
13324
+ didSetActiveOrganization: false
13325
+ };
13326
+ }
13327
+ let organizations;
13328
+ try {
13329
+ organizations = await options.listOrganizations();
13330
+ } catch (error) {
13331
+ options.onError?.(error);
13332
+ return {
13333
+ activeOrganizationId: null,
13334
+ didSetActiveOrganization: false
13335
+ };
13336
+ }
13337
+ if (organizations.length === 0) {
13338
+ return {
13339
+ activeOrganizationId: null,
13340
+ didSetActiveOrganization: false
13341
+ };
13342
+ }
13343
+ const selectedOrganizationId = normalizeOrganizationId(
13344
+ (options.selectOrganizationId ?? defaultSelectOrganizationId)(organizations)
13345
+ );
13346
+ if (!selectedOrganizationId) {
13347
+ return {
13348
+ activeOrganizationId: null,
13349
+ didSetActiveOrganization: false
13350
+ };
13351
+ }
13352
+ try {
13353
+ await options.setActiveOrganization(selectedOrganizationId);
13354
+ return {
13355
+ activeOrganizationId: selectedOrganizationId,
13356
+ didSetActiveOrganization: true
13357
+ };
13358
+ } catch (error) {
13359
+ options.onError?.(error);
13360
+ return {
13361
+ activeOrganizationId: null,
13362
+ didSetActiveOrganization: false
13363
+ };
13364
+ }
13365
+ }
13366
+
13367
+ 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, ensureActiveOrganization, 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 };
12817
13368
  //# sourceMappingURL=index.js.map
12818
13369
  //# sourceMappingURL=index.js.map