@xylex-group/athena 2.4.1 → 2.7.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 (49) hide show
  1. package/README.md +52 -1
  2. package/bin/athena-js.js +0 -0
  3. package/dist/browser.cjs +2642 -56
  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 +2635 -57
  8. package/dist/browser.js.map +1 -1
  9. package/dist/cli/index.cjs +1648 -239
  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 +1648 -239
  14. package/dist/cli/index.js.map +1 -1
  15. package/dist/cookies.cjs +10 -3
  16. package/dist/cookies.cjs.map +1 -1
  17. package/dist/cookies.d.cts +1 -174
  18. package/dist/cookies.d.ts +1 -174
  19. package/dist/cookies.js +10 -3
  20. package/dist/cookies.js.map +1 -1
  21. package/dist/index-CVcQCGyG.d.cts +174 -0
  22. package/dist/index-CVcQCGyG.d.ts +174 -0
  23. package/dist/index.cjs +2642 -56
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +8 -7
  26. package/dist/index.d.ts +8 -7
  27. package/dist/index.js +2635 -57
  28. package/dist/index.js.map +1 -1
  29. package/dist/model-form-AKYrgede.d.ts +2772 -0
  30. package/dist/model-form-ehfqLuG7.d.cts +2772 -0
  31. package/dist/{pipeline-CR4V15jF.d.ts → pipeline-BUsR9XlO.d.ts} +1 -1
  32. package/dist/{pipeline-DZeExYMA.d.cts → pipeline-BfCWSRYl.d.cts} +1 -1
  33. package/dist/react-email-BQzmXBDE.d.cts +304 -0
  34. package/dist/react-email-BrVRp80B.d.ts +304 -0
  35. package/dist/react.cjs +178 -71
  36. package/dist/react.cjs.map +1 -1
  37. package/dist/react.d.cts +22 -5
  38. package/dist/react.d.ts +22 -5
  39. package/dist/react.js +92 -5
  40. package/dist/react.js.map +1 -1
  41. package/dist/{types-D1JvL21V.d.cts → types-BSIsyss1.d.cts} +1 -1
  42. package/dist/{types-09Q4D86N.d.cts → types-BsyRW49r.d.cts} +3 -3
  43. package/dist/{types-09Q4D86N.d.ts → types-BsyRW49r.d.ts} +3 -3
  44. package/dist/{types-DU3gNdFv.d.ts → types-t_TVqnmp.d.ts} +1 -1
  45. package/package.json +22 -21
  46. package/dist/model-form-4LPnOPAF.d.cts +0 -1383
  47. package/dist/model-form-CO4-LmNC.d.ts +0 -1383
  48. package/dist/react-email-6mOyxBo4.d.cts +0 -657
  49. package/dist/react-email-Buhcpglm.d.ts +0 -657
package/dist/browser.js CHANGED
@@ -125,6 +125,60 @@ function buildAthenaGatewayUrl(baseUrl, path) {
125
125
  return `${baseUrl}${path}`;
126
126
  }
127
127
 
128
+ // src/cookies/base64.ts
129
+ function getAtob() {
130
+ const candidate = globalThis.atob;
131
+ return typeof candidate === "function" ? candidate : void 0;
132
+ }
133
+ function getBtoa() {
134
+ const candidate = globalThis.btoa;
135
+ return typeof candidate === "function" ? candidate : void 0;
136
+ }
137
+ function bytesToBinaryString(bytes) {
138
+ let result = "";
139
+ for (const byte of bytes) {
140
+ result += String.fromCharCode(byte);
141
+ }
142
+ return result;
143
+ }
144
+ function binaryStringToBytes(binary) {
145
+ const bytes = new Uint8Array(binary.length);
146
+ for (let i = 0; i < binary.length; i++) {
147
+ bytes[i] = binary.charCodeAt(i);
148
+ }
149
+ return bytes;
150
+ }
151
+ function encodeBase64(bytes) {
152
+ const btoaFn = getBtoa();
153
+ if (btoaFn) {
154
+ return btoaFn(bytesToBinaryString(bytes));
155
+ }
156
+ return Buffer.from(bytes).toString("base64");
157
+ }
158
+ function decodeBase64(base64) {
159
+ const atobFn = getAtob();
160
+ if (atobFn) {
161
+ return binaryStringToBytes(atobFn(base64));
162
+ }
163
+ return new Uint8Array(Buffer.from(base64, "base64"));
164
+ }
165
+ function encodeBytesToBase64Url(bytes) {
166
+ return encodeBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
167
+ }
168
+ function encodeStringToBase64Url(value) {
169
+ const bytes = new TextEncoder().encode(value);
170
+ return encodeBytesToBase64Url(bytes);
171
+ }
172
+ function decodeBase64UrlToBytes(value) {
173
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
174
+ const paddingLength = normalized.length % 4;
175
+ const padded = paddingLength === 0 ? normalized : `${normalized}${"=".repeat(4 - paddingLength)}`;
176
+ return decodeBase64(padded);
177
+ }
178
+ function decodeBase64UrlToString(value) {
179
+ return new TextDecoder().decode(decodeBase64UrlToBytes(value));
180
+ }
181
+
128
182
  // src/cookies/cookie-utils.ts
129
183
  var SECURE_COOKIE_PREFIX = "__Secure-";
130
184
  function parseCookies(cookieHeader) {
@@ -136,24 +190,615 @@ function parseCookies(cookieHeader) {
136
190
  });
137
191
  return cookieMap;
138
192
  }
193
+
194
+ // src/cookies/crypto.ts
195
+ var HS256_ALG = "HS256";
196
+ async function getSubtleCrypto() {
197
+ const globalCrypto = globalThis.crypto;
198
+ if (globalCrypto?.subtle) {
199
+ return globalCrypto.subtle;
200
+ }
201
+ const { webcrypto } = await import('crypto');
202
+ const subtle = webcrypto.subtle;
203
+ if (!subtle) {
204
+ throw new Error("Web Crypto subtle API is unavailable.");
205
+ }
206
+ return subtle;
207
+ }
208
+ async function importHmacKey(secret, usage) {
209
+ const subtle = await getSubtleCrypto();
210
+ return subtle.importKey(
211
+ "raw",
212
+ new TextEncoder().encode(secret),
213
+ {
214
+ name: "HMAC",
215
+ hash: "SHA-256"
216
+ },
217
+ false,
218
+ [usage]
219
+ );
220
+ }
221
+ function bufferToBytes(buffer) {
222
+ return new Uint8Array(buffer);
223
+ }
224
+ function parseJwtPayload(payloadSegment) {
225
+ try {
226
+ const decoded = decodeBase64UrlToString(payloadSegment);
227
+ const payload = JSON.parse(decoded);
228
+ if (!payload || typeof payload !== "object") {
229
+ return null;
230
+ }
231
+ return payload;
232
+ } catch {
233
+ return null;
234
+ }
235
+ }
236
+ function isJwtExpired(payload) {
237
+ const exp = payload.exp;
238
+ if (typeof exp !== "number") {
239
+ return false;
240
+ }
241
+ return exp < Math.floor(Date.now() / 1e3);
242
+ }
243
+ async function signHmacBase64Url(secret, value) {
244
+ const subtle = await getSubtleCrypto();
245
+ const key = await importHmacKey(secret, "sign");
246
+ const signature = await subtle.sign("HMAC", key, new TextEncoder().encode(value));
247
+ return encodeBytesToBase64Url(bufferToBytes(signature));
248
+ }
249
+ async function signJwtHS256(payload, secret, expiresIn = 60 * 5) {
250
+ const now = Math.floor(Date.now() / 1e3);
251
+ const header = { alg: HS256_ALG, typ: "JWT" };
252
+ const fullPayload = {
253
+ ...payload,
254
+ iat: now,
255
+ exp: now + expiresIn
256
+ };
257
+ const headerPart = encodeStringToBase64Url(JSON.stringify(header));
258
+ const payloadPart = encodeStringToBase64Url(JSON.stringify(fullPayload));
259
+ const message = `${headerPart}.${payloadPart}`;
260
+ const signature = await signHmacBase64Url(secret, message);
261
+ return `${message}.${signature}`;
262
+ }
263
+ async function verifyJwtHS256(token, secret) {
264
+ const parts = token.split(".");
265
+ if (parts.length !== 3) {
266
+ return null;
267
+ }
268
+ const [headerPart, payloadPart, signaturePart] = parts;
269
+ if (!headerPart || !payloadPart || !signaturePart) {
270
+ return null;
271
+ }
272
+ let header = null;
273
+ try {
274
+ header = JSON.parse(decodeBase64UrlToString(headerPart));
275
+ } catch {
276
+ return null;
277
+ }
278
+ if (!header || header.alg !== HS256_ALG) {
279
+ return null;
280
+ }
281
+ const payload = parseJwtPayload(payloadPart);
282
+ if (!payload) {
283
+ return null;
284
+ }
285
+ const expectedSignature = await signHmacBase64Url(secret, `${headerPart}.${payloadPart}`);
286
+ if (expectedSignature !== signaturePart) {
287
+ return null;
288
+ }
289
+ if (isJwtExpired(payload)) {
290
+ return null;
291
+ }
292
+ return payload;
293
+ }
294
+
295
+ // src/cookies/session-store.ts
296
+ var ALLOWED_COOKIE_SIZE = 4096;
297
+ var ESTIMATED_EMPTY_COOKIE_SIZE = 200;
298
+ var CHUNK_SIZE = ALLOWED_COOKIE_SIZE - ESTIMATED_EMPTY_COOKIE_SIZE;
299
+ function getChunkIndex(cookieName) {
300
+ const parts = cookieName.split(".");
301
+ const lastPart = parts[parts.length - 1];
302
+ const index = parseInt(lastPart || "0", 10);
303
+ return Number.isNaN(index) ? 0 : index;
304
+ }
305
+ function readExistingChunks(cookieName, ctx) {
306
+ const chunks = {};
307
+ const cookies = parseCookies(ctx.headers?.get("cookie") || "");
308
+ for (const [name, value] of cookies) {
309
+ if (name.startsWith(cookieName)) {
310
+ chunks[name] = value;
311
+ }
312
+ }
313
+ return chunks;
314
+ }
315
+ function joinChunks(chunks) {
316
+ const sortedKeys = Object.keys(chunks).sort((left, right) => getChunkIndex(left) - getChunkIndex(right));
317
+ return sortedKeys.map((key) => chunks[key]).join("");
318
+ }
319
+ function chunkCookie(storeName, cookie, chunks, ctx) {
320
+ const chunkCount = Math.ceil(cookie.value.length / CHUNK_SIZE);
321
+ if (chunkCount === 1) {
322
+ chunks[cookie.name] = cookie.value;
323
+ return [cookie];
324
+ }
325
+ const cookies = [];
326
+ for (let index = 0; index < chunkCount; index++) {
327
+ const name = `${cookie.name}.${index}`;
328
+ const start = index * CHUNK_SIZE;
329
+ const value = cookie.value.substring(start, start + CHUNK_SIZE);
330
+ cookies.push({
331
+ ...cookie,
332
+ name,
333
+ value
334
+ });
335
+ chunks[name] = value;
336
+ }
337
+ ctx.logger?.debug?.(`CHUNKING_${storeName.toUpperCase()}_COOKIE`, {
338
+ message: `${storeName} cookie exceeds allowed ${ALLOWED_COOKIE_SIZE} bytes.`,
339
+ emptyCookieSize: ESTIMATED_EMPTY_COOKIE_SIZE,
340
+ valueSize: cookie.value.length,
341
+ chunkCount,
342
+ chunks: cookies.map((entry) => entry.value.length + ESTIMATED_EMPTY_COOKIE_SIZE)
343
+ });
344
+ return cookies;
345
+ }
346
+ function getCleanCookies(chunks, cookieOptions) {
347
+ const cleanedChunks = {};
348
+ for (const name in chunks) {
349
+ cleanedChunks[name] = {
350
+ name,
351
+ value: "",
352
+ attributes: {
353
+ ...cookieOptions,
354
+ maxAge: 0
355
+ }
356
+ };
357
+ }
358
+ return cleanedChunks;
359
+ }
360
+ var storeFactory = (storeName) => (cookieName, cookieOptions, ctx) => {
361
+ const chunks = readExistingChunks(cookieName, ctx);
362
+ return {
363
+ getValue() {
364
+ return joinChunks(chunks);
365
+ },
366
+ hasChunks() {
367
+ return Object.keys(chunks).length > 0;
368
+ },
369
+ chunk(value, options) {
370
+ const cleanedChunks = getCleanCookies(chunks, cookieOptions);
371
+ for (const name in chunks) {
372
+ delete chunks[name];
373
+ }
374
+ const cookies = cleanedChunks;
375
+ const chunked = chunkCookie(
376
+ storeName,
377
+ {
378
+ name: cookieName,
379
+ value,
380
+ attributes: {
381
+ ...cookieOptions,
382
+ ...options
383
+ }
384
+ },
385
+ chunks,
386
+ ctx
387
+ );
388
+ for (const chunk of chunked) {
389
+ cookies[chunk.name] = chunk;
390
+ }
391
+ return Object.values(cookies);
392
+ },
393
+ clean() {
394
+ const cleanedChunks = getCleanCookies(chunks, cookieOptions);
395
+ for (const name in chunks) {
396
+ delete chunks[name];
397
+ }
398
+ return Object.values(cleanedChunks);
399
+ },
400
+ setCookies(cookies) {
401
+ for (const cookie of cookies) {
402
+ ctx.setCookie(cookie.name, cookie.value, cookie.attributes);
403
+ }
404
+ }
405
+ };
406
+ };
407
+ var createSessionStore = storeFactory("Session");
408
+ var createAccountStore = storeFactory("Account");
409
+
410
+ // src/cookies/index.ts
411
+ var DEFAULT_COOKIE_PREFIX = "athena-auth";
412
+ var LEGACY_COOKIE_PREFIX = "better-auth";
413
+ var DEFAULT_SESSION_MAX_AGE = 7 * 24 * 60 * 60;
414
+ var DEFAULT_CACHE_MAX_AGE = 60 * 5;
415
+ function isProductionRuntime() {
416
+ return typeof process !== "undefined" && process.env?.NODE_ENV === "production";
417
+ }
418
+ function getEnvironmentSecret() {
419
+ if (typeof process === "undefined") {
420
+ return void 0;
421
+ }
422
+ return process.env?.ATHENA_AUTH_SECRET || process.env?.BETTER_AUTH_SECRET || process.env?.AUTH_SECRET;
423
+ }
424
+ function isDynamicBaseURLConfig(baseURL) {
425
+ return typeof baseURL === "object" && baseURL !== null && "allowedHosts" in baseURL && Array.isArray(baseURL.allowedHosts);
426
+ }
427
+ function resolveCookiePrefixes(primaryPrefix) {
428
+ const prefixes = [primaryPrefix];
429
+ if (!prefixes.includes(DEFAULT_COOKIE_PREFIX)) {
430
+ prefixes.push(DEFAULT_COOKIE_PREFIX);
431
+ }
432
+ if (!prefixes.includes(LEGACY_COOKIE_PREFIX)) {
433
+ prefixes.push(LEGACY_COOKIE_PREFIX);
434
+ }
435
+ return prefixes;
436
+ }
437
+ function createError(message) {
438
+ return new Error(`@xylex-group/athena/cookies: ${message}`);
439
+ }
440
+ function getSecretOrThrow(secret) {
441
+ const resolved = secret || getEnvironmentSecret();
442
+ if (!resolved) {
443
+ throw createError(
444
+ "getCookieCache requires a secret. Pass `secret` or set ATHENA_AUTH_SECRET/BETTER_AUTH_SECRET/AUTH_SECRET."
445
+ );
446
+ }
447
+ return resolved;
448
+ }
449
+ function asObject(value) {
450
+ if (!value || typeof value !== "object") {
451
+ return null;
452
+ }
453
+ return value;
454
+ }
455
+ function getSessionTokenFromPair(session) {
456
+ const token = session.session?.token;
457
+ if (typeof token !== "string" || token.length === 0) {
458
+ throw createError("setSessionCookie requires `session.session.token` to be a non-empty string.");
459
+ }
460
+ return token;
461
+ }
462
+ async function resolveCookieVersion(versionConfig, session, user) {
463
+ if (!versionConfig) {
464
+ return "1";
465
+ }
466
+ if (typeof versionConfig === "string") {
467
+ return versionConfig;
468
+ }
469
+ return versionConfig(session, user);
470
+ }
471
+ function getSessionCookieCacheName(cookiePrefix, cookieName, isSecure) {
472
+ return isSecure ? `${SECURE_COOKIE_PREFIX}${cookiePrefix}.${cookieName}` : `${cookiePrefix}.${cookieName}`;
473
+ }
474
+ async function setCookieValue(ctx, name, value, attributes) {
475
+ const secret = ctx.context.secret;
476
+ if (secret && typeof ctx.setSignedCookie === "function") {
477
+ await ctx.setSignedCookie(name, value, secret, attributes);
478
+ return;
479
+ }
480
+ ctx.setCookie(name, value, attributes);
481
+ }
482
+ function parseJsonSafely(value) {
483
+ try {
484
+ return JSON.parse(value);
485
+ } catch {
486
+ return null;
487
+ }
488
+ }
489
+ function getIsSecureCookie(config) {
490
+ if (config?.isSecure !== void 0) {
491
+ return config.isSecure;
492
+ }
493
+ return isProductionRuntime();
494
+ }
495
+ function createCookieGetter(options) {
496
+ const baseURLString = typeof options.baseURL === "string" ? options.baseURL : void 0;
497
+ const dynamicProtocol = typeof options.baseURL === "object" && options.baseURL !== null ? options.baseURL.protocol : void 0;
498
+ const secure = options.advanced?.useSecureCookies !== void 0 ? options.advanced.useSecureCookies : dynamicProtocol === "https" ? true : dynamicProtocol === "http" ? false : baseURLString ? baseURLString.startsWith("https://") : isProductionRuntime();
499
+ const secureCookiePrefix = secure ? SECURE_COOKIE_PREFIX : "";
500
+ const crossSubdomainEnabled = !!options.advanced?.crossSubDomainCookies?.enabled;
501
+ const domain = crossSubdomainEnabled ? options.advanced?.crossSubDomainCookies?.domain || (baseURLString ? new URL(baseURLString).hostname : void 0) : void 0;
502
+ if (crossSubdomainEnabled && !domain && !isDynamicBaseURLConfig(options.baseURL)) {
503
+ throw createError("baseURL is required when `crossSubDomainCookies.enabled` is true.");
504
+ }
505
+ function createCookie(cookieName, overrideAttributes = {}) {
506
+ const prefix = options.advanced?.cookiePrefix || DEFAULT_COOKIE_PREFIX;
507
+ const name = options.advanced?.cookies?.[cookieName]?.name || `${prefix}.${cookieName}`;
508
+ const attributes = options.advanced?.cookies?.[cookieName]?.attributes || {};
509
+ return {
510
+ name: `${secureCookiePrefix}${name}`,
511
+ attributes: {
512
+ secure: !!secureCookiePrefix,
513
+ sameSite: "lax",
514
+ path: "/",
515
+ httpOnly: true,
516
+ ...crossSubdomainEnabled ? { domain } : {},
517
+ ...options.advanced?.defaultCookieAttributes,
518
+ ...overrideAttributes,
519
+ ...attributes
520
+ }
521
+ };
522
+ }
523
+ return createCookie;
524
+ }
525
+ function getCookies(options) {
526
+ const createCookie = createCookieGetter(options);
527
+ const sessionToken = createCookie("session_token", { maxAge: options.session?.expiresIn || DEFAULT_SESSION_MAX_AGE });
528
+ const sessionData = createCookie("session_data", { maxAge: options.session?.cookieCache?.maxAge || DEFAULT_CACHE_MAX_AGE });
529
+ const accountData = createCookie("account_data", { maxAge: options.session?.cookieCache?.maxAge || DEFAULT_CACHE_MAX_AGE });
530
+ const dontRememberToken = createCookie("dont_remember");
531
+ return {
532
+ sessionToken: {
533
+ name: sessionToken.name,
534
+ attributes: sessionToken.attributes
535
+ },
536
+ sessionData: {
537
+ name: sessionData.name,
538
+ attributes: sessionData.attributes
539
+ },
540
+ dontRememberToken: {
541
+ name: dontRememberToken.name,
542
+ attributes: dontRememberToken.attributes
543
+ },
544
+ accountData: {
545
+ name: accountData.name,
546
+ attributes: accountData.attributes
547
+ }
548
+ };
549
+ }
550
+ async function setCookieCache(ctx, session, dontRememberMe) {
551
+ const cookieCacheConfig = ctx.context.options?.session?.cookieCache;
552
+ if (!cookieCacheConfig?.enabled) {
553
+ return;
554
+ }
555
+ const version = await resolveCookieVersion(
556
+ cookieCacheConfig.version,
557
+ session.session,
558
+ session.user
559
+ );
560
+ const sessionData = {
561
+ session: session.session,
562
+ user: session.user,
563
+ updatedAt: Date.now(),
564
+ version
565
+ };
566
+ const baseAttributes = ctx.context.authCookies.sessionData.attributes;
567
+ const maxAge = dontRememberMe ? void 0 : baseAttributes.maxAge;
568
+ const options = {
569
+ ...baseAttributes,
570
+ maxAge
571
+ };
572
+ const expiresAt = Date.now() + (options.maxAge || 60) * 1e3;
573
+ const strategy = cookieCacheConfig.strategy || "compact";
574
+ const secret = getSecretOrThrow(ctx.context.secret);
575
+ let encoded;
576
+ if (strategy === "jwt") {
577
+ encoded = await signJwtHS256(sessionData, secret, options.maxAge || DEFAULT_CACHE_MAX_AGE);
578
+ } else if (strategy === "jwe") {
579
+ throw createError("`jwe` strategy is not supported by the SDK cookie helper.");
580
+ } else {
581
+ const signature = await signHmacBase64Url(
582
+ secret,
583
+ JSON.stringify({
584
+ ...sessionData,
585
+ expiresAt
586
+ })
587
+ );
588
+ encoded = encodeStringToBase64Url(
589
+ JSON.stringify({
590
+ session: sessionData,
591
+ expiresAt,
592
+ signature
593
+ })
594
+ );
595
+ }
596
+ if (encoded.length > 4093) {
597
+ const store = createSessionStore(ctx.context.authCookies.sessionData.name, options, ctx);
598
+ const cookies = store.chunk(encoded, options);
599
+ store.setCookies(cookies);
600
+ } else {
601
+ const store = createSessionStore(ctx.context.authCookies.sessionData.name, options, ctx);
602
+ if (store.hasChunks()) {
603
+ store.setCookies(store.clean());
604
+ }
605
+ ctx.setCookie(ctx.context.authCookies.sessionData.name, encoded, options);
606
+ }
607
+ }
608
+ async function setSessionCookie(ctx, session, dontRememberMe, overrides) {
609
+ if (dontRememberMe === void 0 && typeof ctx.getSignedCookie === "function" && ctx.context.secret) {
610
+ const existingFlag = await ctx.getSignedCookie(ctx.context.authCookies.dontRememberToken.name, ctx.context.secret);
611
+ dontRememberMe = !!existingFlag;
612
+ }
613
+ const resolvedDontRememberMe = dontRememberMe ?? false;
614
+ const token = getSessionTokenFromPair(session);
615
+ const options = ctx.context.authCookies.sessionToken.attributes;
616
+ const maxAge = resolvedDontRememberMe ? void 0 : ctx.context.sessionConfig?.expiresIn;
617
+ await setCookieValue(ctx, ctx.context.authCookies.sessionToken.name, token, {
618
+ ...options,
619
+ maxAge,
620
+ ...overrides
621
+ });
622
+ if (resolvedDontRememberMe) {
623
+ await setCookieValue(
624
+ ctx,
625
+ ctx.context.authCookies.dontRememberToken.name,
626
+ "true",
627
+ ctx.context.authCookies.dontRememberToken.attributes
628
+ );
629
+ }
630
+ await setCookieCache(ctx, session, resolvedDontRememberMe);
631
+ ctx.context.setNewSession?.(session);
632
+ }
633
+ function expireCookie(ctx, cookie) {
634
+ ctx.setCookie(cookie.name, "", {
635
+ ...cookie.attributes,
636
+ maxAge: 0
637
+ });
638
+ }
639
+ function deleteSessionCookie(ctx, skipDontRememberMe) {
640
+ expireCookie(ctx, ctx.context.authCookies.sessionToken);
641
+ expireCookie(ctx, ctx.context.authCookies.sessionData);
642
+ if (ctx.context.options?.account?.storeAccountCookie) {
643
+ expireCookie(ctx, ctx.context.authCookies.accountData);
644
+ const accountStore = createAccountStore(
645
+ ctx.context.authCookies.accountData.name,
646
+ ctx.context.authCookies.accountData.attributes,
647
+ ctx
648
+ );
649
+ accountStore.setCookies(accountStore.clean());
650
+ }
651
+ const sessionStore = createSessionStore(
652
+ ctx.context.authCookies.sessionData.name,
653
+ ctx.context.authCookies.sessionData.attributes,
654
+ ctx
655
+ );
656
+ sessionStore.setCookies(sessionStore.clean());
657
+ if (!skipDontRememberMe) {
658
+ expireCookie(ctx, ctx.context.authCookies.dontRememberToken);
659
+ }
660
+ }
139
661
  var getSessionCookie = (request, config) => {
140
662
  const cookies = (request instanceof Headers || !("headers" in request) ? request : request.headers).get("cookie");
141
663
  if (!cookies) {
142
664
  return null;
143
665
  }
144
- const { cookieName = "session_token", cookiePrefix = "athena-auth" } = {};
666
+ const { cookieName = "session_token", cookiePrefix = "athena-auth" } = config || {};
145
667
  const parsedCookie = parseCookies(cookies);
146
668
  const getCookie = (name) => parsedCookie.get(name) || parsedCookie.get(`${SECURE_COOKIE_PREFIX}${name}`);
147
- const sessionToken = getCookie(`${cookiePrefix}.${cookieName}`) || getCookie(`${cookiePrefix}-${cookieName}`);
148
- if (sessionToken) {
149
- return sessionToken;
669
+ const candidateCookieNames = Array.from(/* @__PURE__ */ new Set([
670
+ cookieName,
671
+ cookieName.replace(/_/g, "-"),
672
+ cookieName.replace(/-/g, "_")
673
+ ])).filter(Boolean);
674
+ for (const candidateName of candidateCookieNames) {
675
+ const sessionToken = getCookie(`${cookiePrefix}.${candidateName}`) || getCookie(`${cookiePrefix}-${candidateName}`);
676
+ if (sessionToken) {
677
+ return sessionToken;
678
+ }
150
679
  }
151
680
  return null;
152
681
  };
682
+ var getCookieCache = async (request, config) => {
683
+ const headers = request instanceof Headers || !("headers" in request) ? request : request.headers;
684
+ const cookieHeader = headers.get("cookie");
685
+ if (!cookieHeader) {
686
+ return null;
687
+ }
688
+ const parsedCookie = parseCookies(cookieHeader);
689
+ const cookieName = config?.cookieName || "session_data";
690
+ const requestedPrefix = config?.cookiePrefix || DEFAULT_COOKIE_PREFIX;
691
+ const strategy = config?.strategy || "compact";
692
+ const cookiePrefixes = resolveCookiePrefixes(requestedPrefix);
693
+ const isSecure = getIsSecureCookie(config);
694
+ const secret = getSecretOrThrow(config?.secret);
695
+ let sessionData;
696
+ for (const prefix of cookiePrefixes) {
697
+ const candidate = getSessionCookieCacheName(prefix, cookieName, isSecure);
698
+ const cookieValue = parsedCookie.get(candidate);
699
+ if (cookieValue) {
700
+ sessionData = cookieValue;
701
+ break;
702
+ }
703
+ }
704
+ if (!sessionData) {
705
+ const reconstructedChunks = [];
706
+ for (const prefix of cookiePrefixes) {
707
+ const candidate = getSessionCookieCacheName(prefix, cookieName, isSecure);
708
+ for (const [name, value] of parsedCookie.entries()) {
709
+ if (!name.startsWith(`${candidate}.`)) {
710
+ continue;
711
+ }
712
+ const parts = name.split(".");
713
+ const indexStr = parts[parts.length - 1];
714
+ const index = parseInt(indexStr || "0", 10);
715
+ if (!Number.isNaN(index)) {
716
+ reconstructedChunks.push({ index, value });
717
+ }
718
+ }
719
+ if (reconstructedChunks.length > 0) {
720
+ break;
721
+ }
722
+ }
723
+ if (reconstructedChunks.length > 0) {
724
+ reconstructedChunks.sort((left, right) => left.index - right.index);
725
+ sessionData = reconstructedChunks.map((chunk) => chunk.value).join("");
726
+ }
727
+ }
728
+ if (!sessionData) {
729
+ return null;
730
+ }
731
+ if (strategy === "jwe") {
732
+ throw createError(
733
+ "`jwe` strategy is not supported by the SDK cookie helper. Use compact/jwt or pass cookie data through the auth server."
734
+ );
735
+ }
736
+ if (strategy === "jwt") {
737
+ const payload = await verifyJwtHS256(sessionData, secret);
738
+ if (!payload) {
739
+ return null;
740
+ }
741
+ const sessionRecord = asObject(payload.session);
742
+ const userRecord = asObject(payload.user);
743
+ const updatedAt = payload.updatedAt;
744
+ if (!sessionRecord || !userRecord || typeof updatedAt !== "number") {
745
+ return null;
746
+ }
747
+ if (config?.version) {
748
+ const cookieVersion = typeof payload.version === "string" ? payload.version : "1";
749
+ const expectedVersion = typeof config.version === "string" ? config.version : await config.version(sessionRecord, userRecord);
750
+ if (cookieVersion !== expectedVersion) {
751
+ return null;
752
+ }
753
+ }
754
+ return {
755
+ session: sessionRecord,
756
+ user: userRecord,
757
+ updatedAt,
758
+ version: typeof payload.version === "string" ? payload.version : void 0
759
+ };
760
+ }
761
+ const compactPayload = parseJsonSafely(decodeBase64UrlToString(sessionData));
762
+ if (!compactPayload) {
763
+ return null;
764
+ }
765
+ const expectedSignature = await signHmacBase64Url(
766
+ secret,
767
+ JSON.stringify({
768
+ ...compactPayload.session,
769
+ expiresAt: compactPayload.expiresAt
770
+ })
771
+ );
772
+ if (expectedSignature !== compactPayload.signature) {
773
+ return null;
774
+ }
775
+ if (compactPayload.expiresAt <= Date.now()) {
776
+ return null;
777
+ }
778
+ const resolvedSession = compactPayload.session;
779
+ if (config?.version) {
780
+ const cookieVersion = resolvedSession.version || "1";
781
+ const expectedVersion = typeof config.version === "string" ? config.version : await config.version(resolvedSession.session, resolvedSession.user);
782
+ if (cookieVersion !== expectedVersion) {
783
+ return null;
784
+ }
785
+ }
786
+ const sessionObject = asObject(resolvedSession.session);
787
+ const userObject = asObject(resolvedSession.user);
788
+ if (!sessionObject || !userObject) {
789
+ return null;
790
+ }
791
+ return {
792
+ session: sessionObject,
793
+ user: userObject,
794
+ updatedAt: resolvedSession.updatedAt,
795
+ version: resolvedSession.version
796
+ };
797
+ };
153
798
 
154
799
  // package.json
155
800
  var package_default = {
156
- version: "2.4.1"
801
+ version: "2.7.0"
157
802
  };
158
803
 
159
804
  // src/sdk-version.ts
@@ -2690,42 +3335,1450 @@ async function withRetry(config, fn) {
2690
3335
  if (!retry) {
2691
3336
  throw error;
2692
3337
  }
2693
- const delay = computeDelayMs(currentAttempt, error, resolvedConfig);
2694
- await sleep(delay);
3338
+ const delay = computeDelayMs(currentAttempt, error, resolvedConfig);
3339
+ await sleep(delay);
3340
+ }
3341
+ }
3342
+ throw new Error("withRetry reached an unexpected state");
3343
+ }
3344
+
3345
+ // src/db/module.ts
3346
+ function createDbModule(input) {
3347
+ const db = {
3348
+ from(table, options) {
3349
+ return input.from(table, options);
3350
+ },
3351
+ select(table, columns, options) {
3352
+ return input.from(table).select(columns, options);
3353
+ },
3354
+ insert(table, values, options) {
3355
+ return Array.isArray(values) ? input.from(table).insert(values, options) : input.from(table).insert(values, options);
3356
+ },
3357
+ upsert(table, values, options) {
3358
+ return Array.isArray(values) ? input.from(table).upsert(values, options) : input.from(table).upsert(values, options);
3359
+ },
3360
+ update(table, values, options) {
3361
+ return input.from(table).update(values, options);
3362
+ },
3363
+ delete(table, options) {
3364
+ return input.from(table).delete(options);
3365
+ },
3366
+ rpc(fn, args, options) {
3367
+ return input.rpc(fn, args, options);
3368
+ },
3369
+ query(query, options) {
3370
+ return input.query(query, options);
3371
+ }
3372
+ };
3373
+ return db;
3374
+ }
3375
+
3376
+ // src/storage/file.ts
3377
+ function createStorageFileModule(base, config = {}) {
3378
+ const upload = async (input, options) => {
3379
+ const sources = normalizeUploadSources(input);
3380
+ validateUploadConstraints(sources, input);
3381
+ const uploadRequests = sources.map((source, index) => {
3382
+ const storageKey = resolveUploadStorageKey(input, source, index, options, config);
3383
+ return {
3384
+ source,
3385
+ uploadRequest: {
3386
+ s3_id: input.s3_id,
3387
+ bucket: input.bucket,
3388
+ storage_key: storageKey,
3389
+ name: input.name ?? source.fileName,
3390
+ original_name: input.original_name ?? source.fileName,
3391
+ resource_id: input.resource_id ?? input.resourceId,
3392
+ mime_type: input.mime_type ?? source.contentType,
3393
+ content_type: input.content_type ?? source.contentType,
3394
+ size_bytes: source.sizeBytes,
3395
+ public: input.public,
3396
+ metadata: input.metadata
3397
+ }
3398
+ };
3399
+ });
3400
+ input.onProgress?.(createProgressSnapshot("preparing", sources, 0, 0, 0));
3401
+ const uploadUrls = uploadRequests.length === 1 ? [await base.createStorageUploadUrl(uploadRequests[0].uploadRequest, options)] : (await base.createStorageUploadUrls({ files: uploadRequests.map((request) => request.uploadRequest) }, options)).files;
3402
+ const aggregateLoaded = new Array(uploadRequests.length).fill(0);
3403
+ const uploaded = [];
3404
+ for (let index = 0; index < uploadRequests.length; index += 1) {
3405
+ const request = uploadRequests[index];
3406
+ const uploadUrl = uploadUrls[index];
3407
+ const response = await putUploadBody(uploadUrl.upload.url, request.source, input, options, (progress) => {
3408
+ aggregateLoaded[index] = progress.loaded;
3409
+ input.onProgress?.(createProgressSnapshot("uploading", sources, index, progress.loaded, sum(aggregateLoaded)));
3410
+ });
3411
+ uploaded.push({
3412
+ file: uploadUrl.file,
3413
+ upload: uploadUrl.upload,
3414
+ source: request.source.source,
3415
+ fileName: request.source.fileName,
3416
+ storage_key: request.uploadRequest.storage_key,
3417
+ response
3418
+ });
3419
+ aggregateLoaded[index] = request.source.sizeBytes;
3420
+ input.onProgress?.(createProgressSnapshot("complete", sources, index, request.source.sizeBytes, sum(aggregateLoaded)));
3421
+ }
3422
+ return {
3423
+ files: uploaded,
3424
+ count: uploaded.length
3425
+ };
3426
+ };
3427
+ const download = ((input, queryOrOptions, maybeOptions) => {
3428
+ const { fileIds, query, options } = normalizeDownloadArgs(input, queryOrOptions, maybeOptions);
3429
+ const downloads = fileIds.map((fileId) => base.getStorageFileProxy(fileId, query, options));
3430
+ return Array.isArray(input) || isRecord5(input) && Array.isArray(input.fileIds) ? Promise.all(downloads) : downloads[0];
3431
+ });
3432
+ const deleteFile = ((input, options) => {
3433
+ if (Array.isArray(input)) {
3434
+ return Promise.all(input.map((fileId) => base.deleteStorageFile(fileId, options)));
3435
+ }
3436
+ return base.deleteStorageFile(input, options);
3437
+ });
3438
+ return {
3439
+ upload,
3440
+ download,
3441
+ list(input, options) {
3442
+ const prefix = resolveStoragePath(input.prefix ?? "", input, options, config);
3443
+ return base.listStorageFiles(
3444
+ {
3445
+ s3_id: input.s3_id,
3446
+ prefix
3447
+ },
3448
+ options
3449
+ );
3450
+ },
3451
+ delete: deleteFile
3452
+ };
3453
+ }
3454
+ function resolveStoragePath(path, input, options, config = {}) {
3455
+ const context = createPathContext(input, options, config);
3456
+ const prefixPath = input.prefixPath ?? config.prefixPath;
3457
+ const prefix = typeof prefixPath === "function" ? prefixPath(context) : prefixPath;
3458
+ return joinStoragePath(renderStorageTemplate(prefix ?? "", context), renderStorageTemplate(path, context));
3459
+ }
3460
+ function resolveUploadStorageKey(input, source, index, options, config) {
3461
+ const explicitKey = input.storage_key ?? input.storageKey;
3462
+ const keyTemplate = input.storageKeyTemplate;
3463
+ const fallbackName = source.fileName;
3464
+ const context = createPathContext(input, options, config);
3465
+ const key = keyTemplate ? renderStorageTemplate(keyTemplate, {
3466
+ ...context,
3467
+ vars: {
3468
+ ...context.vars,
3469
+ index,
3470
+ fileName: source.fileName,
3471
+ name: source.fileName
3472
+ }
3473
+ }) : explicitKey ?? fallbackName;
3474
+ return resolveStoragePath(key, input, options, config);
3475
+ }
3476
+ function normalizeUploadSources(input) {
3477
+ const files = toArray(input.files);
3478
+ if (files.length === 0) {
3479
+ throw new Error("athena.storage.file.upload requires at least one file");
3480
+ }
3481
+ return files.map((source, index) => {
3482
+ const fileName = input.fileName ?? sourceName(source) ?? `file-${index + 1}`;
3483
+ const sizeBytes = sourceSize(source);
3484
+ const contentType = input.content_type ?? input.mime_type ?? sourceContentType(source);
3485
+ return {
3486
+ source,
3487
+ fileName,
3488
+ sizeBytes,
3489
+ contentType
3490
+ };
3491
+ });
3492
+ }
3493
+ function validateUploadConstraints(sources, input) {
3494
+ const maxFiles = input.maxFiles ?? 1;
3495
+ if (sources.length > maxFiles) {
3496
+ throw new Error(`athena.storage.file.upload accepts at most ${maxFiles} file${maxFiles === 1 ? "" : "s"} for this call`);
3497
+ }
3498
+ const maxFileSizeBytes = input.maxFileSizeBytes ?? (input.maxFileSizeMb === void 0 ? void 0 : Math.floor(input.maxFileSizeMb * 1024 * 1024));
3499
+ if (maxFileSizeBytes !== void 0) {
3500
+ const tooLarge = sources.find((source) => source.sizeBytes > maxFileSizeBytes);
3501
+ if (tooLarge) {
3502
+ throw new Error(`athena.storage.file.upload rejected ${tooLarge.fileName}: file exceeds ${maxFileSizeBytes} bytes`);
3503
+ }
3504
+ }
3505
+ const allowedExtensions = normalizeExtensions(input.allowedExtensions ?? input.extensions);
3506
+ if (allowedExtensions.size > 0) {
3507
+ const invalid = sources.find((source) => !allowedExtensions.has(fileExtension(source.fileName)));
3508
+ if (invalid) {
3509
+ throw new Error(`athena.storage.file.upload rejected ${invalid.fileName}: extension is not allowed`);
3510
+ }
3511
+ }
3512
+ }
3513
+ async function putUploadBody(url, source, input, options, onProgress) {
3514
+ const headers = new Headers(input.uploadHeaders);
3515
+ if (source.contentType && !headers.has("Content-Type")) {
3516
+ headers.set("Content-Type", source.contentType);
3517
+ }
3518
+ if (typeof XMLHttpRequest !== "undefined") {
3519
+ return putUploadBodyWithXhr(url, source, headers, options, onProgress);
3520
+ }
3521
+ onProgress({ loaded: 0 });
3522
+ const response = await fetch(url, {
3523
+ method: "PUT",
3524
+ headers,
3525
+ body: source.source,
3526
+ signal: options?.signal
3527
+ });
3528
+ if (!response.ok) {
3529
+ throw new Error(`athena.storage.file.upload failed with status ${response.status}`);
3530
+ }
3531
+ onProgress({ loaded: source.sizeBytes });
3532
+ return response;
3533
+ }
3534
+ function putUploadBodyWithXhr(url, source, headers, options, onProgress) {
3535
+ const Xhr = XMLHttpRequest;
3536
+ if (Xhr === void 0) {
3537
+ return Promise.reject(new Error("athena.storage.file.upload requires XMLHttpRequest in this runtime"));
3538
+ }
3539
+ return new Promise((resolve, reject) => {
3540
+ const xhr = new Xhr();
3541
+ const abort = () => xhr.abort();
3542
+ xhr.open("PUT", url);
3543
+ headers.forEach((value, key) => xhr.setRequestHeader(key, value));
3544
+ xhr.upload.onprogress = (event) => {
3545
+ onProgress({ loaded: event.loaded });
3546
+ };
3547
+ xhr.onload = () => {
3548
+ if (options?.signal) {
3549
+ options.signal.removeEventListener("abort", abort);
3550
+ }
3551
+ if (xhr.status < 200 || xhr.status >= 300) {
3552
+ reject(new Error(`athena.storage.file.upload failed with status ${xhr.status}`));
3553
+ return;
3554
+ }
3555
+ onProgress({ loaded: source.sizeBytes });
3556
+ resolve(new Response(xhr.response, {
3557
+ status: xhr.status,
3558
+ statusText: xhr.statusText,
3559
+ headers: parseXhrHeaders(xhr.getAllResponseHeaders())
3560
+ }));
3561
+ };
3562
+ xhr.onerror = () => {
3563
+ if (options?.signal) {
3564
+ options.signal.removeEventListener("abort", abort);
3565
+ }
3566
+ reject(new Error("athena.storage.file.upload failed with a network error"));
3567
+ };
3568
+ xhr.onabort = () => {
3569
+ if (options?.signal) {
3570
+ options.signal.removeEventListener("abort", abort);
3571
+ }
3572
+ reject(new DOMException("Upload aborted", "AbortError"));
3573
+ };
3574
+ if (options?.signal) {
3575
+ if (options.signal.aborted) {
3576
+ abort();
3577
+ return;
3578
+ }
3579
+ options.signal.addEventListener("abort", abort, { once: true });
3580
+ }
3581
+ xhr.send(source.source);
3582
+ });
3583
+ }
3584
+ function normalizeDownloadArgs(input, queryOrOptions, maybeOptions) {
3585
+ if (typeof input === "string") {
3586
+ return { fileIds: [input], query: queryOrOptions, options: maybeOptions };
3587
+ }
3588
+ if (Array.isArray(input)) {
3589
+ return { fileIds: [...input], query: queryOrOptions, options: maybeOptions };
3590
+ }
3591
+ const downloadInput = input;
3592
+ const { fileId, fileIds, ...query } = downloadInput;
3593
+ return {
3594
+ fileIds: fileIds ? [...fileIds] : fileId ? [fileId] : [],
3595
+ query,
3596
+ options: queryOrOptions
3597
+ };
3598
+ }
3599
+ function createPathContext(input, options, config) {
3600
+ const organizationId = input.organizationId ?? input.organization_id ?? options?.organizationId ?? void 0;
3601
+ const userId = input.userId ?? input.user_id ?? options?.userId ?? void 0;
3602
+ const resourceId = input.resourceId ?? input.resource_id ?? void 0;
3603
+ const vars = {
3604
+ ...config.vars ?? {},
3605
+ ...input.vars ?? {}
3606
+ };
3607
+ if (organizationId !== void 0) {
3608
+ vars.organizationId = organizationId;
3609
+ vars.organization_id = organizationId;
3610
+ }
3611
+ if (userId !== void 0) {
3612
+ vars.userId = userId;
3613
+ vars.user_id = userId;
3614
+ }
3615
+ if (resourceId !== void 0) {
3616
+ vars.resourceId = resourceId;
3617
+ vars.resource_id = resourceId;
3618
+ }
3619
+ return {
3620
+ vars,
3621
+ env: {
3622
+ ...readProcessEnv(),
3623
+ ...config.env ?? {},
3624
+ ...input.env ?? {}
3625
+ },
3626
+ organizationId,
3627
+ organization_id: organizationId,
3628
+ userId,
3629
+ user_id: userId,
3630
+ resourceId,
3631
+ resource_id: resourceId
3632
+ };
3633
+ }
3634
+ function renderStorageTemplate(template, context) {
3635
+ return template.replace(/\$\{([^}]+)\}|\{([^}]+)\}/g, (_match, shellToken, braceToken) => {
3636
+ const token = (shellToken ?? braceToken ?? "").trim();
3637
+ if (!token) return "";
3638
+ const value = resolveTemplateToken(token, context);
3639
+ return value === void 0 || value === null ? "" : String(value);
3640
+ });
3641
+ }
3642
+ function resolveTemplateToken(token, context) {
3643
+ if (token.startsWith("env.")) {
3644
+ return context.env[token.slice(4)];
3645
+ }
3646
+ if (token in context.vars) {
3647
+ return context.vars[token];
3648
+ }
3649
+ return context.env[token];
3650
+ }
3651
+ function joinStoragePath(...parts) {
3652
+ return parts.map((part) => part.trim().replace(/^\/+|\/+$/g, "")).filter(Boolean).join("/");
3653
+ }
3654
+ function toArray(files) {
3655
+ if (isUploadSource(files)) return [files];
3656
+ return Array.from(files);
3657
+ }
3658
+ function isUploadSource(value) {
3659
+ return value instanceof Blob || value instanceof ArrayBuffer || value instanceof Uint8Array;
3660
+ }
3661
+ function sourceName(source) {
3662
+ return isRecord5(source) && typeof source.name === "string" && source.name.trim() ? source.name.trim() : void 0;
3663
+ }
3664
+ function sourceSize(source) {
3665
+ if (source instanceof Blob) return source.size;
3666
+ return source.byteLength;
3667
+ }
3668
+ function sourceContentType(source) {
3669
+ return source instanceof Blob && source.type.trim() ? source.type.trim() : void 0;
3670
+ }
3671
+ function normalizeExtensions(extensions) {
3672
+ return new Set((extensions ?? []).map((extension) => extension.replace(/^\./, "").toLowerCase()).filter(Boolean));
3673
+ }
3674
+ function fileExtension(fileName) {
3675
+ const lastDot = fileName.lastIndexOf(".");
3676
+ return lastDot === -1 ? "" : fileName.slice(lastDot + 1).toLowerCase();
3677
+ }
3678
+ function createProgressSnapshot(phase, sources, fileIndex, loaded, aggregateLoaded) {
3679
+ const total = sources[fileIndex]?.sizeBytes ?? 0;
3680
+ const aggregateTotal = sources.reduce((totalBytes, source) => totalBytes + source.sizeBytes, 0);
3681
+ return {
3682
+ phase,
3683
+ fileIndex,
3684
+ fileCount: sources.length,
3685
+ fileName: sources[fileIndex]?.fileName ?? "",
3686
+ loaded,
3687
+ total,
3688
+ percent: total > 0 ? Math.round(loaded / total * 100) : 100,
3689
+ aggregateLoaded,
3690
+ aggregateTotal,
3691
+ aggregatePercent: aggregateTotal > 0 ? Math.round(aggregateLoaded / aggregateTotal * 100) : 100
3692
+ };
3693
+ }
3694
+ function sum(values) {
3695
+ return values.reduce((total, value) => total + value, 0);
3696
+ }
3697
+ function parseXhrHeaders(raw) {
3698
+ const headers = new Headers();
3699
+ for (const line of raw.trim().split(/[\r\n]+/)) {
3700
+ const index = line.indexOf(":");
3701
+ if (index === -1) continue;
3702
+ headers.set(line.slice(0, index).trim(), line.slice(index + 1).trim());
3703
+ }
3704
+ return headers;
3705
+ }
3706
+ function readProcessEnv() {
3707
+ const processLike = globalThis.process;
3708
+ return processLike?.env ?? {};
3709
+ }
3710
+ function isRecord5(value) {
3711
+ return Boolean(value) && typeof value === "object";
3712
+ }
3713
+
3714
+ // src/storage/module.ts
3715
+ var storageSdkManifest = {
3716
+ namespace: "storage",
3717
+ basePath: "/storage",
3718
+ envelopeKinds: {
3719
+ raw: "response body is the payload",
3720
+ athena: "response body is { status, message, data }"
3721
+ },
3722
+ methods: [
3723
+ {
3724
+ name: "listStorageCatalogs",
3725
+ method: "GET",
3726
+ path: "/storage/catalogs",
3727
+ responseEnvelope: "raw",
3728
+ responseType: "{ data: S3CatalogItem[] }"
3729
+ },
3730
+ {
3731
+ name: "createStorageCatalog",
3732
+ method: "POST",
3733
+ path: "/storage/catalogs",
3734
+ requestType: "CreateStorageCatalogRequest",
3735
+ responseEnvelope: "raw",
3736
+ responseType: "S3CatalogItem"
3737
+ },
3738
+ {
3739
+ name: "updateStorageCatalog",
3740
+ method: "PATCH",
3741
+ path: "/storage/catalogs/{id}",
3742
+ pathParams: ["id"],
3743
+ requestType: "UpdateStorageCatalogRequest",
3744
+ responseEnvelope: "raw",
3745
+ responseType: "S3CatalogItem"
3746
+ },
3747
+ {
3748
+ name: "deleteStorageCatalog",
3749
+ method: "DELETE",
3750
+ path: "/storage/catalogs/{id}",
3751
+ pathParams: ["id"],
3752
+ responseEnvelope: "raw",
3753
+ responseType: "{ id: string; deleted: boolean }"
3754
+ },
3755
+ {
3756
+ name: "listStorageCredentials",
3757
+ method: "GET",
3758
+ path: "/storage/credentials",
3759
+ responseEnvelope: "raw",
3760
+ responseType: "{ data: S3CredentialListItem[] }"
3761
+ },
3762
+ {
3763
+ name: "createStorageUploadUrl",
3764
+ method: "POST",
3765
+ path: "/storage/files/upload-url",
3766
+ requestType: "CreateStorageUploadUrlRequest",
3767
+ responseEnvelope: "athena",
3768
+ responseType: "StorageUploadUrlResponse"
3769
+ },
3770
+ {
3771
+ name: "createStorageUploadUrls",
3772
+ method: "POST",
3773
+ path: "/storage/files/upload-urls",
3774
+ requestType: "CreateStorageUploadUrlsRequest",
3775
+ responseEnvelope: "athena",
3776
+ responseType: "StorageBatchUploadUrlResponse"
3777
+ },
3778
+ {
3779
+ name: "listStorageFiles",
3780
+ method: "POST",
3781
+ path: "/storage/files/list",
3782
+ requestType: "ListStorageFilesRequest",
3783
+ responseEnvelope: "athena",
3784
+ responseType: "StorageListFilesResponse"
3785
+ },
3786
+ {
3787
+ name: "getStorageFile",
3788
+ method: "GET",
3789
+ path: "/storage/files/{file_id}",
3790
+ pathParams: ["file_id"],
3791
+ responseEnvelope: "athena",
3792
+ responseType: "StorageFileMutationResponse"
3793
+ },
3794
+ {
3795
+ name: "getStorageFileUrl",
3796
+ method: "GET",
3797
+ path: "/storage/files/{file_id}/url",
3798
+ pathParams: ["file_id"],
3799
+ queryParams: ["purpose"],
3800
+ responseEnvelope: "athena",
3801
+ responseType: "PresignedFileUrlResponse"
3802
+ },
3803
+ {
3804
+ name: "getStorageFileProxy",
3805
+ method: "GET",
3806
+ path: "/storage/files/{file_id}/proxy",
3807
+ pathParams: ["file_id"],
3808
+ queryParams: ["purpose"],
3809
+ responseEnvelope: "raw",
3810
+ responseType: "Response",
3811
+ binary: true
3812
+ },
3813
+ {
3814
+ name: "updateStorageFile",
3815
+ method: "PATCH",
3816
+ path: "/storage/files/{file_id}",
3817
+ pathParams: ["file_id"],
3818
+ requestType: "UpdateStorageFileRequest",
3819
+ responseEnvelope: "athena",
3820
+ responseType: "StorageFileMutationResponse"
3821
+ },
3822
+ {
3823
+ name: "deleteStorageFile",
3824
+ method: "DELETE",
3825
+ path: "/storage/files/{file_id}",
3826
+ pathParams: ["file_id"],
3827
+ responseEnvelope: "athena",
3828
+ responseType: "StorageFileMutationResponse"
3829
+ },
3830
+ {
3831
+ name: "setStorageFileVisibility",
3832
+ method: "PATCH",
3833
+ path: "/storage/files/{file_id}/visibility",
3834
+ pathParams: ["file_id"],
3835
+ requestType: "SetStorageFileVisibilityRequest",
3836
+ responseEnvelope: "athena",
3837
+ responseType: "StorageFileMutationResponse"
3838
+ },
3839
+ {
3840
+ name: "deleteStorageFolder",
3841
+ method: "POST",
3842
+ path: "/storage/folders/delete",
3843
+ requestType: "DeleteStorageFolderRequest",
3844
+ responseEnvelope: "athena",
3845
+ responseType: "StorageFolderMutationResponse"
3846
+ },
3847
+ {
3848
+ name: "moveStorageFolder",
3849
+ method: "POST",
3850
+ path: "/storage/folders/move",
3851
+ requestType: "MoveStorageFolderRequest",
3852
+ responseEnvelope: "athena",
3853
+ responseType: "StorageFolderMutationResponse"
3854
+ }
3855
+ ]
3856
+ };
3857
+ var AthenaStorageErrorCode = {
3858
+ InvalidUrl: "INVALID_URL",
3859
+ NetworkError: "NETWORK_ERROR",
3860
+ HttpError: "HTTP_ERROR",
3861
+ InvalidJson: "INVALID_JSON",
3862
+ InvalidAthenaEnvelope: "INVALID_ATHENA_ENVELOPE",
3863
+ UnknownError: "UNKNOWN_ERROR"
3864
+ };
3865
+ var AthenaStorageError = class extends Error {
3866
+ code;
3867
+ athenaCode;
3868
+ kind;
3869
+ category;
3870
+ retryable;
3871
+ status;
3872
+ endpoint;
3873
+ method;
3874
+ requestId;
3875
+ hint;
3876
+ causeDetail;
3877
+ raw;
3878
+ normalized;
3879
+ __athenaNormalizedError;
3880
+ constructor(input) {
3881
+ super(input.message, { cause: input.cause });
3882
+ this.name = "AthenaStorageError";
3883
+ this.code = input.code;
3884
+ this.status = input.status;
3885
+ this.endpoint = input.endpoint;
3886
+ this.method = input.method;
3887
+ this.requestId = input.requestId;
3888
+ this.hint = input.hint;
3889
+ this.causeDetail = causeToString(input.cause);
3890
+ this.raw = input.raw ?? null;
3891
+ this.normalized = normalizeStorageErrorInput(input);
3892
+ this.__athenaNormalizedError = this.normalized;
3893
+ this.athenaCode = this.normalized.code;
3894
+ this.kind = this.normalized.kind;
3895
+ this.category = this.normalized.category;
3896
+ this.retryable = this.normalized.retryable;
3897
+ Object.defineProperty(this, "__athenaNormalizedError", {
3898
+ value: this.normalized,
3899
+ enumerable: false,
3900
+ configurable: false,
3901
+ writable: false
3902
+ });
3903
+ }
3904
+ toDetails() {
3905
+ return {
3906
+ code: this.code,
3907
+ athenaCode: this.athenaCode,
3908
+ kind: this.kind,
3909
+ category: this.category,
3910
+ retryable: this.retryable,
3911
+ message: this.message,
3912
+ status: this.status,
3913
+ endpoint: this.endpoint,
3914
+ method: this.method,
3915
+ requestId: this.requestId,
3916
+ hint: this.hint,
3917
+ cause: this.causeDetail,
3918
+ raw: this.raw
3919
+ };
3920
+ }
3921
+ };
3922
+ function isRecord6(value) {
3923
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
3924
+ }
3925
+ function causeToString(cause) {
3926
+ if (cause === void 0 || cause === null) return void 0;
3927
+ if (typeof cause === "string") return cause;
3928
+ if (cause instanceof Error && cause.message.trim()) return cause.message.trim();
3929
+ try {
3930
+ return JSON.stringify(cause);
3931
+ } catch {
3932
+ return String(cause);
3933
+ }
3934
+ }
3935
+ function storageGatewayCode(code) {
3936
+ if (code === "INVALID_URL") return "INVALID_URL";
3937
+ if (code === "NETWORK_ERROR") return "NETWORK_ERROR";
3938
+ if (code === "INVALID_JSON" || code === "INVALID_ATHENA_ENVELOPE") return "INVALID_JSON";
3939
+ if (code === "HTTP_ERROR") return "HTTP_ERROR";
3940
+ return "UNKNOWN_ERROR";
3941
+ }
3942
+ function headerValue(headers, names) {
3943
+ for (const name of names) {
3944
+ const value = headers.get(name);
3945
+ if (value?.trim()) return value.trim();
3946
+ }
3947
+ return void 0;
3948
+ }
3949
+ function storageOperationFromEndpoint(endpoint, method) {
3950
+ const endpointPath = String(endpoint).split("?")[0];
3951
+ for (const candidate of storageSdkManifest.methods) {
3952
+ if (candidate.method !== method) continue;
3953
+ const pattern = `^${candidate.path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\{[^/]+\\\}/g, "[^/]+")}$`;
3954
+ if (new RegExp(pattern).test(endpointPath)) {
3955
+ return candidate.name;
3956
+ }
3957
+ }
3958
+ return `storage:${method.toLowerCase()}`;
3959
+ }
3960
+ function normalizeStorageErrorInput(input) {
3961
+ return normalizeAthenaError(
3962
+ {
3963
+ data: null,
3964
+ error: {
3965
+ message: input.message,
3966
+ gatewayCode: storageGatewayCode(input.code),
3967
+ status: input.status,
3968
+ raw: input.raw ?? input.cause ?? null
3969
+ },
3970
+ errorDetails: {
3971
+ code: storageGatewayCode(input.code),
3972
+ message: input.message,
3973
+ status: input.status,
3974
+ endpoint: input.endpoint,
3975
+ method: input.method,
3976
+ requestId: input.requestId,
3977
+ hint: input.hint,
3978
+ cause: causeToString(input.cause)
3979
+ },
3980
+ raw: input.raw ?? input.cause ?? null,
3981
+ status: input.status
3982
+ },
3983
+ { operation: storageOperationFromEndpoint(input.endpoint, input.method) }
3984
+ );
3985
+ }
3986
+ function createAthenaStorageError(input) {
3987
+ return new AthenaStorageError(input);
3988
+ }
3989
+ async function notifyStorageError(error, options, runtimeOptions) {
3990
+ const handlers = [runtimeOptions?.onError, options?.onError].filter(
3991
+ (handler) => typeof handler === "function"
3992
+ );
3993
+ for (const handler of handlers) {
3994
+ try {
3995
+ await handler(error);
3996
+ } catch {
3997
+ }
3998
+ }
3999
+ }
4000
+ async function rejectStorageError(input, options, runtimeOptions) {
4001
+ const error = createAthenaStorageError(input);
4002
+ await notifyStorageError(error, options, runtimeOptions);
4003
+ throw error;
4004
+ }
4005
+ function parseResponseBody3(rawText, contentType) {
4006
+ if (!rawText) {
4007
+ return { parsed: null, parseFailed: false };
4008
+ }
4009
+ const contentTypeSuggestsJson = contentType?.toLowerCase().includes("application/json") ?? false;
4010
+ const looksJson = contentTypeSuggestsJson || rawText.startsWith("{") || rawText.startsWith("[");
4011
+ if (!looksJson) {
4012
+ return { parsed: rawText, parseFailed: false };
4013
+ }
4014
+ try {
4015
+ return { parsed: JSON.parse(rawText), parseFailed: false };
4016
+ } catch {
4017
+ return { parsed: rawText, parseFailed: true };
4018
+ }
4019
+ }
4020
+ function appendQuery(path, query) {
4021
+ if (!query) return path;
4022
+ const params = new URLSearchParams();
4023
+ for (const [key, value] of Object.entries(query)) {
4024
+ if (value === void 0 || value === null) continue;
4025
+ params.set(key, String(value));
4026
+ }
4027
+ const queryText = params.toString();
4028
+ return queryText ? `${path}?${queryText}` : path;
4029
+ }
4030
+ function storagePath(path) {
4031
+ return path;
4032
+ }
4033
+ function withPathParam(path, name, value) {
4034
+ return path.replace(`{${name}}`, encodeURIComponent(value));
4035
+ }
4036
+ function resolveErrorMessage3(payload, fallback) {
4037
+ if (isRecord6(payload)) {
4038
+ const message = payload.message ?? payload.error ?? payload.details;
4039
+ if (typeof message === "string" && message.trim()) {
4040
+ return message.trim();
4041
+ }
4042
+ }
4043
+ if (typeof payload === "string" && payload.trim()) {
4044
+ return payload.trim();
4045
+ }
4046
+ return fallback;
4047
+ }
4048
+ function resolveErrorHint2(payload) {
4049
+ if (!isRecord6(payload)) return void 0;
4050
+ const hint = payload.hint ?? payload.suggestion;
4051
+ return typeof hint === "string" && hint.trim() ? hint.trim() : void 0;
4052
+ }
4053
+ function resolveErrorCause(payload) {
4054
+ if (!isRecord6(payload)) return void 0;
4055
+ const cause = payload.cause ?? payload.reason;
4056
+ return typeof cause === "string" && cause.trim() ? cause.trim() : void 0;
4057
+ }
4058
+ function storageCodeFromUnknown(error) {
4059
+ if (isAthenaGatewayError(error)) {
4060
+ if (error.code === "INVALID_URL") return "INVALID_URL";
4061
+ if (error.code === "NETWORK_ERROR") return "NETWORK_ERROR";
4062
+ if (error.code === "INVALID_JSON") return "INVALID_JSON";
4063
+ if (error.code === "HTTP_ERROR") return "HTTP_ERROR";
4064
+ }
4065
+ return "UNKNOWN_ERROR";
4066
+ }
4067
+ async function callStorageEndpoint(gateway, endpoint, method, envelope, payload, options, runtimeOptions) {
4068
+ let url;
4069
+ let headers;
4070
+ try {
4071
+ const baseUrl = options?.baseUrl ? normalizeAthenaGatewayBaseUrl(options.baseUrl) : gateway.baseUrl;
4072
+ url = buildAthenaGatewayUrl(baseUrl, endpoint);
4073
+ headers = gateway.buildHeaders(options);
4074
+ } catch (error) {
4075
+ return rejectStorageError(
4076
+ {
4077
+ code: storageCodeFromUnknown(error),
4078
+ message: error instanceof Error ? error.message : `Athena storage ${method} ${endpoint} failed before sending the request`,
4079
+ status: isAthenaGatewayError(error) ? error.status : 0,
4080
+ endpoint,
4081
+ method,
4082
+ raw: error,
4083
+ requestId: isAthenaGatewayError(error) ? error.requestId : void 0,
4084
+ hint: isAthenaGatewayError(error) ? error.hint : void 0,
4085
+ cause: error
4086
+ },
4087
+ options,
4088
+ runtimeOptions
4089
+ );
4090
+ }
4091
+ const requestInit = {
4092
+ method,
4093
+ headers,
4094
+ signal: options?.signal
4095
+ };
4096
+ if (payload !== void 0 && method !== "GET") {
4097
+ requestInit.body = JSON.stringify(payload);
4098
+ }
4099
+ let response;
4100
+ try {
4101
+ response = await fetch(url, requestInit);
4102
+ } catch (error) {
4103
+ const message = error instanceof Error ? error.message : String(error);
4104
+ return rejectStorageError(
4105
+ {
4106
+ code: "NETWORK_ERROR",
4107
+ message: `Network error while calling Athena storage ${method} ${endpoint}: ${message}`,
4108
+ status: 0,
4109
+ endpoint,
4110
+ method,
4111
+ cause: error
4112
+ },
4113
+ options,
4114
+ runtimeOptions
4115
+ );
4116
+ }
4117
+ let rawText;
4118
+ try {
4119
+ rawText = await response.text();
4120
+ } catch (error) {
4121
+ return rejectStorageError(
4122
+ {
4123
+ code: "NETWORK_ERROR",
4124
+ message: `Athena storage ${method} ${endpoint} response body could not be read`,
4125
+ status: response.status,
4126
+ endpoint,
4127
+ method,
4128
+ requestId: headerValue(response.headers, ["x-athena-request-id", "x-request-id", "request-id"]),
4129
+ cause: error
4130
+ },
4131
+ options,
4132
+ runtimeOptions
4133
+ );
4134
+ }
4135
+ const parsedBody = parseResponseBody3(rawText ?? "", response.headers.get("content-type"));
4136
+ const requestId = headerValue(response.headers, ["x-athena-request-id", "x-request-id", "request-id"]);
4137
+ if (parsedBody.parseFailed) {
4138
+ return rejectStorageError(
4139
+ {
4140
+ code: "INVALID_JSON",
4141
+ message: `Athena storage ${method} ${endpoint} returned malformed JSON`,
4142
+ status: response.status,
4143
+ endpoint,
4144
+ method,
4145
+ requestId,
4146
+ raw: parsedBody.parsed
4147
+ },
4148
+ options,
4149
+ runtimeOptions
4150
+ );
4151
+ }
4152
+ if (!response.ok) {
4153
+ return rejectStorageError(
4154
+ {
4155
+ code: "HTTP_ERROR",
4156
+ message: resolveErrorMessage3(
4157
+ parsedBody.parsed,
4158
+ `Athena storage ${method} ${endpoint} failed with status ${response.status}`
4159
+ ),
4160
+ status: response.status,
4161
+ endpoint,
4162
+ method,
4163
+ requestId,
4164
+ hint: resolveErrorHint2(parsedBody.parsed),
4165
+ cause: resolveErrorCause(parsedBody.parsed),
4166
+ raw: parsedBody.parsed
4167
+ },
4168
+ options,
4169
+ runtimeOptions
4170
+ );
4171
+ }
4172
+ if (envelope === "athena") {
4173
+ if (!isRecord6(parsedBody.parsed) || !("data" in parsedBody.parsed)) {
4174
+ return rejectStorageError(
4175
+ {
4176
+ code: "INVALID_ATHENA_ENVELOPE",
4177
+ message: `Athena storage ${method} ${endpoint} returned an invalid Athena envelope`,
4178
+ status: response.status,
4179
+ endpoint,
4180
+ method,
4181
+ requestId,
4182
+ raw: parsedBody.parsed
4183
+ },
4184
+ options,
4185
+ runtimeOptions
4186
+ );
4187
+ }
4188
+ return parsedBody.parsed.data;
4189
+ }
4190
+ return parsedBody.parsed;
4191
+ }
4192
+ async function callStorageBinaryEndpoint(gateway, endpoint, method, options, runtimeOptions) {
4193
+ let url;
4194
+ let headers;
4195
+ try {
4196
+ const baseUrl = options?.baseUrl ? normalizeAthenaGatewayBaseUrl(options.baseUrl) : gateway.baseUrl;
4197
+ url = buildAthenaGatewayUrl(baseUrl, endpoint);
4198
+ headers = gateway.buildHeaders(options);
4199
+ } catch (error) {
4200
+ return rejectStorageError(
4201
+ {
4202
+ code: storageCodeFromUnknown(error),
4203
+ message: error instanceof Error ? error.message : `Athena storage ${method} ${endpoint} failed before sending the request`,
4204
+ status: isAthenaGatewayError(error) ? error.status : 0,
4205
+ endpoint,
4206
+ method,
4207
+ raw: error,
4208
+ requestId: isAthenaGatewayError(error) ? error.requestId : void 0,
4209
+ hint: isAthenaGatewayError(error) ? error.hint : void 0,
4210
+ cause: error
4211
+ },
4212
+ options,
4213
+ runtimeOptions
4214
+ );
4215
+ }
4216
+ let response;
4217
+ try {
4218
+ response = await fetch(url, {
4219
+ method,
4220
+ headers,
4221
+ signal: options?.signal
4222
+ });
4223
+ } catch (error) {
4224
+ const message = error instanceof Error ? error.message : String(error);
4225
+ return rejectStorageError(
4226
+ {
4227
+ code: "NETWORK_ERROR",
4228
+ message: `Network error while calling Athena storage ${method} ${endpoint}: ${message}`,
4229
+ status: 0,
4230
+ endpoint,
4231
+ method,
4232
+ cause: error
4233
+ },
4234
+ options,
4235
+ runtimeOptions
4236
+ );
4237
+ }
4238
+ if (response.ok) {
4239
+ return response;
4240
+ }
4241
+ const requestId = headerValue(response.headers, ["x-athena-request-id", "x-request-id", "request-id"]);
4242
+ let rawErrorBody = null;
4243
+ try {
4244
+ const rawText = await response.text();
4245
+ const parsedBody = parseResponseBody3(rawText ?? "", response.headers.get("content-type"));
4246
+ rawErrorBody = parsedBody.parsed;
4247
+ } catch (error) {
4248
+ return rejectStorageError(
4249
+ {
4250
+ code: "NETWORK_ERROR",
4251
+ message: `Athena storage ${method} ${endpoint} error response body could not be read`,
4252
+ status: response.status,
4253
+ endpoint,
4254
+ method,
4255
+ requestId,
4256
+ cause: error
4257
+ },
4258
+ options,
4259
+ runtimeOptions
4260
+ );
4261
+ }
4262
+ return rejectStorageError(
4263
+ {
4264
+ code: "HTTP_ERROR",
4265
+ message: resolveErrorMessage3(
4266
+ rawErrorBody,
4267
+ `Athena storage ${method} ${endpoint} failed with status ${response.status}`
4268
+ ),
4269
+ status: response.status,
4270
+ endpoint,
4271
+ method,
4272
+ requestId,
4273
+ hint: resolveErrorHint2(rawErrorBody),
4274
+ cause: resolveErrorCause(rawErrorBody),
4275
+ raw: rawErrorBody
4276
+ },
4277
+ options,
4278
+ runtimeOptions
4279
+ );
4280
+ }
4281
+ function isBlobBody(body) {
4282
+ return typeof Blob !== "undefined" && body instanceof Blob;
4283
+ }
4284
+ function isReadableStreamBody(body) {
4285
+ return typeof ReadableStream !== "undefined" && body instanceof ReadableStream;
4286
+ }
4287
+ async function putPresignedUploadBody(uploadUrl, uploadHeaders, body, options) {
4288
+ const headers = new Headers(uploadHeaders);
4289
+ Object.entries(options?.headers ?? {}).forEach(([key, value]) => headers.set(key, value));
4290
+ if (!headers.has("Content-Type") && isBlobBody(body) && body.type) {
4291
+ headers.set("Content-Type", body.type);
4292
+ }
4293
+ const init = {
4294
+ method: "PUT",
4295
+ headers,
4296
+ body,
4297
+ signal: options?.signal
4298
+ };
4299
+ if (isReadableStreamBody(body)) {
4300
+ init.duplex = "half";
4301
+ }
4302
+ return fetch(uploadUrl, init);
4303
+ }
4304
+ function attachManagedUpload(upload) {
4305
+ const headers = {};
4306
+ return {
4307
+ ...upload,
4308
+ method: "PUT",
4309
+ headers,
4310
+ expiresAt: upload.expires_at,
4311
+ put(body, options) {
4312
+ return putPresignedUploadBody(upload.url, headers, body, options);
4313
+ }
4314
+ };
4315
+ }
4316
+ function attachUploadHelper(response) {
4317
+ return {
4318
+ ...response,
4319
+ upload: attachManagedUpload(response.upload)
4320
+ };
4321
+ }
4322
+ function attachUploadHelpers(response) {
4323
+ return {
4324
+ files: response.files.map(attachUploadHelper)
4325
+ };
4326
+ }
4327
+ function normalizeUploadUrlRequest(input) {
4328
+ const s3_id = input.s3_id ?? input.s3Id;
4329
+ const storage_key = input.storage_key ?? input.storageKey;
4330
+ if (!s3_id?.trim()) {
4331
+ throw new Error("athena.storage.file.upload requires s3_id or s3Id");
4332
+ }
4333
+ if (!storage_key?.trim()) {
4334
+ throw new Error("athena.storage.file.upload requires storage_key or storageKey");
4335
+ }
4336
+ const fileName = input.fileName?.trim();
4337
+ const originalName = input.originalName?.trim();
4338
+ return {
4339
+ s3_id,
4340
+ bucket: input.bucket,
4341
+ storage_key,
4342
+ name: input.name ?? fileName,
4343
+ original_name: input.original_name ?? originalName ?? fileName,
4344
+ resource_id: input.resource_id ?? input.resourceId,
4345
+ mime_type: input.mime_type ?? input.mimeType,
4346
+ content_type: input.content_type ?? input.contentType,
4347
+ size_bytes: input.size_bytes ?? input.sizeBytes,
4348
+ file_id: input.file_id ?? input.fileId,
4349
+ public: input.public,
4350
+ visibility: input.visibility,
4351
+ metadata: input.metadata
4352
+ };
4353
+ }
4354
+ async function callStorageUploadBinaryEndpoint(gateway, endpoint, body, options, runtimeOptions) {
4355
+ let url;
4356
+ let headers;
4357
+ try {
4358
+ const baseUrl = options?.baseUrl ? normalizeAthenaGatewayBaseUrl(options.baseUrl) : gateway.baseUrl;
4359
+ url = buildAthenaGatewayUrl(baseUrl, endpoint);
4360
+ headers = gateway.buildHeaders(options);
4361
+ } catch (error) {
4362
+ return rejectStorageError(
4363
+ {
4364
+ code: storageCodeFromUnknown(error),
4365
+ message: error instanceof Error ? error.message : `Athena storage PUT ${endpoint} failed before sending the request`,
4366
+ status: isAthenaGatewayError(error) ? error.status : 0,
4367
+ endpoint,
4368
+ method: "PUT",
4369
+ raw: error,
4370
+ requestId: isAthenaGatewayError(error) ? error.requestId : void 0,
4371
+ hint: isAthenaGatewayError(error) ? error.hint : void 0,
4372
+ cause: error
4373
+ },
4374
+ options,
4375
+ runtimeOptions
4376
+ );
4377
+ }
4378
+ delete headers["Content-Type"];
4379
+ delete headers["content-type"];
4380
+ if (isBlobBody(body) && body.type) {
4381
+ headers["Content-Type"] = body.type;
4382
+ }
4383
+ const requestInit = {
4384
+ method: "PUT",
4385
+ headers,
4386
+ body,
4387
+ signal: options?.signal
4388
+ };
4389
+ if (isReadableStreamBody(body)) {
4390
+ requestInit.duplex = "half";
4391
+ }
4392
+ let response;
4393
+ try {
4394
+ response = await fetch(url, requestInit);
4395
+ } catch (error) {
4396
+ const message = error instanceof Error ? error.message : String(error);
4397
+ return rejectStorageError(
4398
+ {
4399
+ code: "NETWORK_ERROR",
4400
+ message: `Network error while calling Athena storage PUT ${endpoint}: ${message}`,
4401
+ status: 0,
4402
+ endpoint,
4403
+ method: "PUT",
4404
+ cause: error
4405
+ },
4406
+ options,
4407
+ runtimeOptions
4408
+ );
4409
+ }
4410
+ let rawText;
4411
+ try {
4412
+ rawText = await response.text();
4413
+ } catch (error) {
4414
+ return rejectStorageError(
4415
+ {
4416
+ code: "NETWORK_ERROR",
4417
+ message: `Athena storage PUT ${endpoint} response body could not be read`,
4418
+ status: response.status,
4419
+ endpoint,
4420
+ method: "PUT",
4421
+ requestId: headerValue(response.headers, ["x-athena-request-id", "x-request-id", "request-id"]),
4422
+ cause: error
4423
+ },
4424
+ options,
4425
+ runtimeOptions
4426
+ );
4427
+ }
4428
+ const parsedBody = parseResponseBody3(rawText ?? "", response.headers.get("content-type"));
4429
+ const requestId = headerValue(response.headers, ["x-athena-request-id", "x-request-id", "request-id"]);
4430
+ if (parsedBody.parseFailed) {
4431
+ return rejectStorageError(
4432
+ {
4433
+ code: "INVALID_JSON",
4434
+ message: `Athena storage PUT ${endpoint} returned malformed JSON`,
4435
+ status: response.status,
4436
+ endpoint,
4437
+ method: "PUT",
4438
+ requestId,
4439
+ raw: parsedBody.parsed
4440
+ },
4441
+ options,
4442
+ runtimeOptions
4443
+ );
4444
+ }
4445
+ if (!response.ok) {
4446
+ return rejectStorageError(
4447
+ {
4448
+ code: "HTTP_ERROR",
4449
+ message: resolveErrorMessage3(
4450
+ parsedBody.parsed,
4451
+ `Athena storage PUT ${endpoint} failed with status ${response.status}`
4452
+ ),
4453
+ status: response.status,
4454
+ endpoint,
4455
+ method: "PUT",
4456
+ requestId,
4457
+ hint: resolveErrorHint2(parsedBody.parsed),
4458
+ cause: resolveErrorCause(parsedBody.parsed),
4459
+ raw: parsedBody.parsed
4460
+ },
4461
+ options,
4462
+ runtimeOptions
4463
+ );
4464
+ }
4465
+ if (!isRecord6(parsedBody.parsed) || !("data" in parsedBody.parsed)) {
4466
+ return rejectStorageError(
4467
+ {
4468
+ code: "INVALID_ATHENA_ENVELOPE",
4469
+ message: `Athena storage PUT ${endpoint} returned an invalid Athena envelope`,
4470
+ status: response.status,
4471
+ endpoint,
4472
+ method: "PUT",
4473
+ requestId,
4474
+ raw: parsedBody.parsed
4475
+ },
4476
+ options,
4477
+ runtimeOptions
4478
+ );
4479
+ }
4480
+ return parsedBody.parsed.data;
4481
+ }
4482
+ function createStorageModule(gateway, runtimeOptions) {
4483
+ const callRaw = (path, method, payload, options) => callStorageEndpoint(
4484
+ gateway,
4485
+ storagePath(path),
4486
+ method,
4487
+ "raw",
4488
+ payload,
4489
+ options,
4490
+ runtimeOptions
4491
+ );
4492
+ const callAthena2 = (path, method, payload, options) => callStorageEndpoint(
4493
+ gateway,
4494
+ storagePath(path),
4495
+ method,
4496
+ "athena",
4497
+ payload,
4498
+ options,
4499
+ runtimeOptions
4500
+ );
4501
+ const base = {
4502
+ listStorageCatalogs(options) {
4503
+ return callRaw("/storage/catalogs", "GET", void 0, options);
4504
+ },
4505
+ createStorageCatalog(input, options) {
4506
+ return callRaw("/storage/catalogs", "POST", input, options);
4507
+ },
4508
+ updateStorageCatalog(id, input, options) {
4509
+ return callRaw(withPathParam("/storage/catalogs/{id}", "id", id), "PATCH", input, options);
4510
+ },
4511
+ deleteStorageCatalog(id, options) {
4512
+ return callRaw(withPathParam("/storage/catalogs/{id}", "id", id), "DELETE", void 0, options);
4513
+ },
4514
+ listStorageCredentials(options) {
4515
+ return callRaw("/storage/credentials", "GET", void 0, options);
4516
+ },
4517
+ createStorageUploadUrl(input, options) {
4518
+ return callAthena2("/storage/files/upload-url", "POST", input, options);
4519
+ },
4520
+ createStorageUploadUrls(input, options) {
4521
+ return callAthena2("/storage/files/upload-urls", "POST", input, options);
4522
+ },
4523
+ listStorageFiles(input, options) {
4524
+ return callAthena2("/storage/files/list", "POST", input, options);
4525
+ },
4526
+ getStorageFile(fileId, options) {
4527
+ return callAthena2(withPathParam("/storage/files/{file_id}", "file_id", fileId), "GET", void 0, options);
4528
+ },
4529
+ getStorageFileUrl(fileId, query, options) {
4530
+ const path = appendQuery(
4531
+ withPathParam("/storage/files/{file_id}/url", "file_id", fileId),
4532
+ query
4533
+ );
4534
+ return callAthena2(path, "GET", void 0, options);
4535
+ },
4536
+ getStorageFileProxy(fileId, query, options) {
4537
+ const path = appendQuery(
4538
+ withPathParam("/storage/files/{file_id}/proxy", "file_id", fileId),
4539
+ query
4540
+ );
4541
+ return callStorageBinaryEndpoint(gateway, storagePath(path), "GET", options, runtimeOptions);
4542
+ },
4543
+ updateStorageFile(fileId, input, options) {
4544
+ return callAthena2(withPathParam("/storage/files/{file_id}", "file_id", fileId), "PATCH", input, options);
4545
+ },
4546
+ deleteStorageFile(fileId, options) {
4547
+ return callAthena2(withPathParam("/storage/files/{file_id}", "file_id", fileId), "DELETE", void 0, options);
4548
+ },
4549
+ setStorageFileVisibility(fileId, input, options) {
4550
+ return callAthena2(withPathParam("/storage/files/{file_id}/visibility", "file_id", fileId), "PATCH", input, options);
4551
+ },
4552
+ deleteStorageFolder(input, options) {
4553
+ return callAthena2("/storage/folders/delete", "POST", input, options);
4554
+ },
4555
+ moveStorageFolder(input, options) {
4556
+ return callAthena2("/storage/folders/move", "POST", input, options);
4557
+ }
4558
+ };
4559
+ const fileFacade = createStorageFileModule(base, runtimeOptions);
4560
+ const fileUpload = ((input, options) => {
4561
+ if (isRecord6(input) && "files" in input) {
4562
+ return fileFacade.upload(input, options);
4563
+ }
4564
+ return base.createStorageUploadUrl(
4565
+ normalizeUploadUrlRequest(input),
4566
+ options
4567
+ ).then(attachUploadHelper);
4568
+ });
4569
+ const fileDelete = ((input, options) => fileFacade.delete(input, options));
4570
+ const file = {
4571
+ ...fileFacade,
4572
+ upload: fileUpload,
4573
+ uploadMany(input, options) {
4574
+ return base.createStorageUploadUrls(
4575
+ { files: input.files.map(normalizeUploadUrlRequest) },
4576
+ options
4577
+ ).then(attachUploadHelpers);
4578
+ },
4579
+ confirmUpload(fileId, input, options) {
4580
+ return callAthena2(withPathParam("/storage/files/{file_id}/confirm-upload", "file_id", fileId), "POST", input ?? {}, options);
4581
+ },
4582
+ uploadBinary(fileId, body, options) {
4583
+ return callStorageUploadBinaryEndpoint(
4584
+ gateway,
4585
+ storagePath(withPathParam("/storage/files/{file_id}/upload", "file_id", fileId)),
4586
+ body,
4587
+ options,
4588
+ runtimeOptions
4589
+ );
4590
+ },
4591
+ search(input, options) {
4592
+ return callAthena2("/storage/files/search", "POST", input, options);
4593
+ },
4594
+ get(fileId, options) {
4595
+ return base.getStorageFile(fileId, options);
4596
+ },
4597
+ update(fileId, input, options) {
4598
+ return base.updateStorageFile(fileId, input, options);
4599
+ },
4600
+ delete: fileDelete,
4601
+ deleteMany(input, options) {
4602
+ return callAthena2("/storage/files/delete-many", "POST", input, options);
4603
+ },
4604
+ updateMany(input, options) {
4605
+ return callAthena2("/storage/files/update-many", "POST", input, options);
4606
+ },
4607
+ restore(fileId, options) {
4608
+ return callAthena2(withPathParam("/storage/files/{file_id}/restore", "file_id", fileId), "POST", {}, options);
4609
+ },
4610
+ purge(fileId, options) {
4611
+ return callAthena2(withPathParam("/storage/files/{file_id}/purge", "file_id", fileId), "DELETE", void 0, options);
4612
+ },
4613
+ copy(fileId, input, options) {
4614
+ return callAthena2(withPathParam("/storage/files/{file_id}/copy", "file_id", fileId), "POST", input, options);
4615
+ },
4616
+ url(fileId, query, options) {
4617
+ return base.getStorageFileUrl(fileId, query, options);
4618
+ },
4619
+ publicUrl(fileId, options) {
4620
+ return callAthena2(withPathParam("/storage/files/{file_id}/public-url", "file_id", fileId), "GET", void 0, options);
4621
+ },
4622
+ proxy(fileId, query, options) {
4623
+ return base.getStorageFileProxy(fileId, query, options);
4624
+ },
4625
+ visibility: {
4626
+ set(fileId, input, options) {
4627
+ return base.setStorageFileVisibility(fileId, input, options);
4628
+ },
4629
+ setMany(input, options) {
4630
+ return callAthena2("/storage/files/visibility-many", "POST", input, options);
4631
+ }
2695
4632
  }
2696
- }
2697
- throw new Error("withRetry reached an unexpected state");
2698
- }
2699
-
2700
- // src/db/module.ts
2701
- function createDbModule(input) {
2702
- const db = {
2703
- from(table, options) {
2704
- return input.from(table, options);
4633
+ };
4634
+ const credentials = {
4635
+ list(options) {
4636
+ return base.listStorageCredentials(options);
4637
+ }
4638
+ };
4639
+ const catalog = {
4640
+ list(options) {
4641
+ return base.listStorageCatalogs(options);
2705
4642
  },
2706
- select(table, columns, options) {
2707
- return input.from(table).select(columns, options);
4643
+ create(input, options) {
4644
+ return base.createStorageCatalog(input, options);
2708
4645
  },
2709
- insert(table, values, options) {
2710
- return Array.isArray(values) ? input.from(table).insert(values, options) : input.from(table).insert(values, options);
4646
+ update(id, input, options) {
4647
+ return base.updateStorageCatalog(id, input, options);
2711
4648
  },
2712
- upsert(table, values, options) {
2713
- return Array.isArray(values) ? input.from(table).upsert(values, options) : input.from(table).upsert(values, options);
4649
+ delete(id, options) {
4650
+ return base.deleteStorageCatalog(id, options);
4651
+ }
4652
+ };
4653
+ const folder = {
4654
+ list(input, options) {
4655
+ return callAthena2("/storage/folders/list", "POST", input, options);
2714
4656
  },
2715
- update(table, values, options) {
2716
- return input.from(table).update(values, options);
4657
+ tree(input, options) {
4658
+ return callAthena2("/storage/folders/tree", "POST", input, options);
2717
4659
  },
2718
- delete(table, options) {
2719
- return input.from(table).delete(options);
4660
+ delete(input, options) {
4661
+ return base.deleteStorageFolder(input, options);
2720
4662
  },
2721
- rpc(fn, args, options) {
2722
- return input.rpc(fn, args, options);
4663
+ move(input, options) {
4664
+ return base.moveStorageFolder(input, options);
4665
+ }
4666
+ };
4667
+ const permission = {
4668
+ list(input, options) {
4669
+ return callAthena2("/storage/permissions/list", "POST", input, options);
2723
4670
  },
2724
- query(query, options) {
2725
- return input.query(query, options);
4671
+ grant(input, options) {
4672
+ return callAthena2("/storage/permissions/grant", "POST", input, options);
4673
+ },
4674
+ revoke(input, options) {
4675
+ return callAthena2("/storage/permissions/revoke", "POST", input, options);
4676
+ },
4677
+ check(input, options) {
4678
+ return callAthena2("/storage/permissions/check", "POST", input, options);
2726
4679
  }
2727
4680
  };
2728
- return db;
4681
+ const objectFolder = {
4682
+ create(input, options) {
4683
+ return callAthena2("/storage/objects/folder", "POST", input, options);
4684
+ },
4685
+ delete(input, options) {
4686
+ return callAthena2("/storage/objects/folder/delete", "POST", input, options);
4687
+ },
4688
+ rename(input, options) {
4689
+ return callAthena2("/storage/objects/folder/rename", "POST", input, options);
4690
+ }
4691
+ };
4692
+ const object = {
4693
+ list(input, options) {
4694
+ return callAthena2("/storage/objects", "POST", input, options);
4695
+ },
4696
+ head(input, options) {
4697
+ return callAthena2("/storage/objects/head", "POST", input, options);
4698
+ },
4699
+ exists(input, options) {
4700
+ return callAthena2("/storage/objects/exists", "POST", input, options);
4701
+ },
4702
+ validate(input, options) {
4703
+ return callAthena2("/storage/objects/validate", "POST", input, options);
4704
+ },
4705
+ update(input, options) {
4706
+ return callAthena2("/storage/objects/update", "POST", input, options);
4707
+ },
4708
+ copy(input, options) {
4709
+ return callAthena2("/storage/objects/copy", "POST", input, options);
4710
+ },
4711
+ url(input, options) {
4712
+ return callAthena2("/storage/objects/url", "POST", input, options);
4713
+ },
4714
+ publicUrl(input, options) {
4715
+ return callAthena2("/storage/objects/public-url", "POST", input, options);
4716
+ },
4717
+ delete(input, options) {
4718
+ return callAthena2("/storage/objects/delete", "POST", input, options);
4719
+ },
4720
+ uploadUrl(input, options) {
4721
+ return callAthena2("/storage/objects/upload-url", "POST", input, options);
4722
+ },
4723
+ folder: objectFolder
4724
+ };
4725
+ const bucket = {
4726
+ list(input, options) {
4727
+ return callAthena2("/storage/buckets/list", "POST", input, options);
4728
+ },
4729
+ create(input, options) {
4730
+ return callAthena2("/storage/buckets/create", "POST", input, options);
4731
+ },
4732
+ delete(input, options) {
4733
+ return callAthena2("/storage/buckets/delete", "POST", input, options);
4734
+ },
4735
+ cors: {
4736
+ get(input, options) {
4737
+ return callAthena2("/storage/buckets/cors", "POST", input, options);
4738
+ },
4739
+ set(input, options) {
4740
+ return callAthena2("/storage/buckets/cors/set", "POST", input, options);
4741
+ },
4742
+ delete(input, options) {
4743
+ return callAthena2("/storage/buckets/cors/delete", "POST", input, options);
4744
+ }
4745
+ }
4746
+ };
4747
+ const multipart = {
4748
+ create(input, options) {
4749
+ return callAthena2("/storage/multipart/create", "POST", input, options);
4750
+ },
4751
+ signPart(input, options) {
4752
+ return callAthena2("/storage/multipart/sign-part", "POST", input, options);
4753
+ },
4754
+ complete(input, options) {
4755
+ return callAthena2("/storage/multipart/complete", "POST", input, options);
4756
+ },
4757
+ abort(input, options) {
4758
+ return callAthena2("/storage/multipart/abort", "POST", input, options);
4759
+ },
4760
+ listParts(input, options) {
4761
+ return callAthena2("/storage/multipart/list-parts", "POST", input, options);
4762
+ }
4763
+ };
4764
+ const audit = {
4765
+ list(input, options) {
4766
+ return callAthena2("/storage/audit/list", "POST", input, options);
4767
+ }
4768
+ };
4769
+ return {
4770
+ ...base,
4771
+ credentials,
4772
+ catalog,
4773
+ file,
4774
+ folder,
4775
+ permission,
4776
+ object,
4777
+ bucket,
4778
+ multipart,
4779
+ audit,
4780
+ delete: file.delete
4781
+ };
2729
4782
  }
2730
4783
 
2731
4784
  // src/query-ast.ts
@@ -2755,7 +4808,7 @@ var BOOLEAN_SAFE_OPERATORS = /* @__PURE__ */ new Set([
2755
4808
  "ilike",
2756
4809
  "is"
2757
4810
  ]);
2758
- function isRecord5(value) {
4811
+ function isRecord7(value) {
2759
4812
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
2760
4813
  }
2761
4814
  function isUuidString(value) {
@@ -2768,7 +4821,7 @@ function shouldUseUuidTextComparison(column, value) {
2768
4821
  return typeof value === "string" && isUuidString(value) && isUuidIdentifierColumn(column);
2769
4822
  }
2770
4823
  function isRelationSelectNode(value) {
2771
- return isRecord5(value) && isRecord5(value.select);
4824
+ return isRecord7(value) && isRecord7(value.select);
2772
4825
  }
2773
4826
  function normalizeIdentifier(value, label) {
2774
4827
  const normalized = value.trim();
@@ -2824,7 +4877,7 @@ function compileRelationToken(key, node) {
2824
4877
  return `${prefix}${relationToken}(${nested})`;
2825
4878
  }
2826
4879
  function compileSelectShape(select) {
2827
- if (!isRecord5(select)) {
4880
+ if (!isRecord7(select)) {
2828
4881
  throw new Error("findMany select must be an object");
2829
4882
  }
2830
4883
  const tokens = [];
@@ -2848,7 +4901,7 @@ function compileSelectShape(select) {
2848
4901
  return tokens.join(",");
2849
4902
  }
2850
4903
  function selectShapeUsesRelationSchema(select) {
2851
- if (!isRecord5(select)) {
4904
+ if (!isRecord7(select)) {
2852
4905
  return false;
2853
4906
  }
2854
4907
  for (const rawValue of Object.values(select)) {
@@ -2866,7 +4919,7 @@ function selectShapeUsesRelationSchema(select) {
2866
4919
  }
2867
4920
  function compileColumnWhere(column, input) {
2868
4921
  const normalizedColumn = normalizeIdentifier(column, "where column");
2869
- if (!isRecord5(input)) {
4922
+ if (!isRecord7(input)) {
2870
4923
  return [buildGatewayCondition("eq", normalizedColumn, input)];
2871
4924
  }
2872
4925
  const conditions = [];
@@ -2894,7 +4947,7 @@ function compileColumnWhere(column, input) {
2894
4947
  return conditions;
2895
4948
  }
2896
4949
  function compileBooleanExpressionTerms(clause, label) {
2897
- if (!isRecord5(clause)) {
4950
+ if (!isRecord7(clause)) {
2898
4951
  throw new Error(`findMany where.${label} clauses must be objects`);
2899
4952
  }
2900
4953
  const entries = Object.entries(clause).filter(([, value]) => value !== void 0);
@@ -2903,7 +4956,7 @@ function compileBooleanExpressionTerms(clause, label) {
2903
4956
  }
2904
4957
  const [rawColumn, rawValue] = entries[0];
2905
4958
  const column = normalizeIdentifier(rawColumn, `where.${label} column`);
2906
- if (!isRecord5(rawValue)) {
4959
+ if (!isRecord7(rawValue)) {
2907
4960
  return [`${column}.eq.${stringifyFilterValue(rawValue)}`];
2908
4961
  }
2909
4962
  const operatorEntries = Object.entries(rawValue).filter(([, value]) => value !== void 0);
@@ -2927,7 +4980,7 @@ function compileWhere(where) {
2927
4980
  if (where === void 0) {
2928
4981
  return void 0;
2929
4982
  }
2930
- if (!isRecord5(where)) {
4983
+ if (!isRecord7(where)) {
2931
4984
  throw new Error("findMany where must be an object");
2932
4985
  }
2933
4986
  const conditions = [];
@@ -2977,7 +5030,7 @@ function compileOrderBy(orderBy) {
2977
5030
  if (orderBy === void 0) {
2978
5031
  return void 0;
2979
5032
  }
2980
- if (!isRecord5(orderBy)) {
5033
+ if (!isRecord7(orderBy)) {
2981
5034
  throw new Error("findMany orderBy must be an object");
2982
5035
  }
2983
5036
  if ("column" in orderBy) {
@@ -3152,11 +5205,11 @@ function toFindManyAstOrder(order) {
3152
5205
  ascending: order.direction !== "descending"
3153
5206
  };
3154
5207
  }
3155
- function isRecord6(value) {
5208
+ function isRecord8(value) {
3156
5209
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
3157
5210
  }
3158
5211
  function normalizeFindManyAstColumnPredicate(value) {
3159
- if (!isRecord6(value)) {
5212
+ if (!isRecord8(value)) {
3160
5213
  return {
3161
5214
  eq: value
3162
5215
  };
@@ -3180,7 +5233,7 @@ function normalizeFindManyAstBooleanOperand(clause) {
3180
5233
  return normalized;
3181
5234
  }
3182
5235
  function normalizeFindManyAstWhere(where) {
3183
- if (!where || !isRecord6(where)) {
5236
+ if (!where || !isRecord8(where)) {
3184
5237
  return where;
3185
5238
  }
3186
5239
  const normalized = {};
@@ -3194,7 +5247,7 @@ function normalizeFindManyAstWhere(where) {
3194
5247
  );
3195
5248
  continue;
3196
5249
  }
3197
- if (key === "not" && isRecord6(value)) {
5250
+ if (key === "not" && isRecord8(value)) {
3198
5251
  normalized.not = normalizeFindManyAstBooleanOperand(
3199
5252
  value
3200
5253
  );
@@ -3205,7 +5258,7 @@ function normalizeFindManyAstWhere(where) {
3205
5258
  return normalized;
3206
5259
  }
3207
5260
  function predicateRequiresUuidQueryFallback(column, value) {
3208
- if (!isRecord6(value)) {
5261
+ if (!isRecord8(value)) {
3209
5262
  return shouldUseUuidTextComparison(column, value);
3210
5263
  }
3211
5264
  const eqValue = value.eq;
@@ -3223,7 +5276,7 @@ function booleanOperandRequiresUuidQueryFallback(clause) {
3223
5276
  return false;
3224
5277
  }
3225
5278
  function findManyAstWhereRequiresLegacyTransport(where) {
3226
- if (!where || !isRecord6(where)) {
5279
+ if (!where || !isRecord8(where)) {
3227
5280
  return false;
3228
5281
  }
3229
5282
  for (const [key, value] of Object.entries(where)) {
@@ -3238,7 +5291,7 @@ function findManyAstWhereRequiresLegacyTransport(where) {
3238
5291
  }
3239
5292
  continue;
3240
5293
  }
3241
- if (key === "not" && isRecord6(value)) {
5294
+ if (key === "not" && isRecord8(value)) {
3242
5295
  if (booleanOperandRequiresUuidQueryFallback(value)) {
3243
5296
  return true;
3244
5297
  }
@@ -3440,7 +5493,7 @@ async function executeExperimentalRead(experimental, runner) {
3440
5493
  throw error;
3441
5494
  }
3442
5495
  }
3443
- function isRecord7(value) {
5496
+ function isRecord9(value) {
3444
5497
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
3445
5498
  }
3446
5499
  function firstNonEmptyString2(...values) {
@@ -3452,8 +5505,8 @@ function firstNonEmptyString2(...values) {
3452
5505
  return void 0;
3453
5506
  }
3454
5507
  function resolveStructuredErrorPayload2(raw) {
3455
- if (!isRecord7(raw)) return null;
3456
- return isRecord7(raw.error) ? raw.error : raw;
5508
+ if (!isRecord9(raw)) return null;
5509
+ return isRecord9(raw.error) ? raw.error : raw;
3457
5510
  }
3458
5511
  function resolveStructuredErrorDetails(payload, message) {
3459
5512
  if (!payload || !("details" in payload)) {
@@ -3469,7 +5522,7 @@ function resolveStructuredErrorDetails(payload, message) {
3469
5522
  return details;
3470
5523
  }
3471
5524
  function createResultError(response, result, normalized) {
3472
- const rawRecord = isRecord7(response.raw) ? response.raw : null;
5525
+ const rawRecord = isRecord9(response.raw) ? response.raw : null;
3473
5526
  const payload = resolveStructuredErrorPayload2(response.raw);
3474
5527
  const message = firstNonEmptyString2(
3475
5528
  response.error,
@@ -4932,7 +6985,7 @@ function createClientFromConfig(config) {
4932
6985
  };
4933
6986
  const query = createQueryBuilder(gateway, formatGatewayResult, config.experimental, queryTracer);
4934
6987
  const db = createDbModule({ from, rpc, query });
4935
- return {
6988
+ const sdkClient = {
4936
6989
  from,
4937
6990
  db,
4938
6991
  rpc,
@@ -4940,6 +6993,14 @@ function createClientFromConfig(config) {
4940
6993
  verifyConnection: gateway.verifyConnection,
4941
6994
  auth: auth.auth
4942
6995
  };
6996
+ if (config.experimental?.athenaStorageBackend) {
6997
+ const storageClient = {
6998
+ ...sdkClient,
6999
+ storage: createStorageModule(gateway, config.experimental.storage)
7000
+ };
7001
+ return storageClient;
7002
+ }
7003
+ return sdkClient;
4943
7004
  }
4944
7005
  var DEFAULT_BACKEND = { type: "athena" };
4945
7006
  function toBackendConfig(b) {
@@ -4970,6 +7031,12 @@ function mergeExperimentalOptions(current, next) {
4970
7031
  ...next.traceQueries
4971
7032
  };
4972
7033
  }
7034
+ if (current?.storage || next.storage) {
7035
+ merged.storage = {
7036
+ ...current?.storage ?? {},
7037
+ ...next.storage ?? {}
7038
+ };
7039
+ }
4973
7040
  return merged;
4974
7041
  }
4975
7042
  var AthenaClientBuilderImpl = class {
@@ -5006,7 +7073,7 @@ var AthenaClientBuilderImpl = class {
5006
7073
  }
5007
7074
  experimental(options) {
5008
7075
  this.experimentalOptions = mergeExperimentalOptions(this.experimentalOptions, options);
5009
- return this;
7076
+ return options.athenaStorageBackend ? this : this;
5010
7077
  }
5011
7078
  options(options) {
5012
7079
  if (options.client !== void 0) {
@@ -5027,7 +7094,7 @@ var AthenaClientBuilderImpl = class {
5027
7094
  if (options.experimental !== void 0) {
5028
7095
  this.experimentalOptions = mergeExperimentalOptions(this.experimentalOptions, options.experimental);
5029
7096
  }
5030
- return this;
7097
+ return options.experimental?.athenaStorageBackend ? this : this;
5031
7098
  }
5032
7099
  build() {
5033
7100
  if (!this.baseUrl || !this.apiKey) {
@@ -5223,7 +7290,7 @@ function resolveNullishValue(mode) {
5223
7290
  if (mode === "null") return null;
5224
7291
  return "";
5225
7292
  }
5226
- function isRecord8(value) {
7293
+ function isRecord10(value) {
5227
7294
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
5228
7295
  }
5229
7296
  function isNullableColumn(model, key) {
@@ -5232,7 +7299,7 @@ function isNullableColumn(model, key) {
5232
7299
  }
5233
7300
  function toModelFormDefaults(model, values, options) {
5234
7301
  const source = values;
5235
- if (!isRecord8(source)) {
7302
+ if (!isRecord10(source)) {
5236
7303
  return {};
5237
7304
  }
5238
7305
  const mode = options?.nullishMode ?? "empty-string";
@@ -5307,6 +7374,90 @@ function resolveProviderSchemas(providerConfig) {
5307
7374
  return [...DEFAULT_POSTGRES_SCHEMAS];
5308
7375
  }
5309
7376
 
7377
+ // src/generator/env.ts
7378
+ function readEnvStringValue(key) {
7379
+ if (typeof process === "undefined" || !process.env) {
7380
+ return void 0;
7381
+ }
7382
+ const value = process.env[key];
7383
+ if (typeof value !== "string") {
7384
+ return void 0;
7385
+ }
7386
+ const trimmed = value.trim();
7387
+ return trimmed.length > 0 ? trimmed : void 0;
7388
+ }
7389
+ function throwMissingEnvVar(key) {
7390
+ throw new Error(
7391
+ `Generator config env var ${key} is missing or empty. Set ${key} or provide a default value.`
7392
+ );
7393
+ }
7394
+ function resolveEnvValue(key, options, resolver) {
7395
+ const rawValue = readEnvStringValue(key);
7396
+ if (rawValue === void 0) {
7397
+ if (options?.default !== void 0) {
7398
+ return options.default;
7399
+ }
7400
+ if (options?.optional) {
7401
+ return void 0;
7402
+ }
7403
+ return throwMissingEnvVar(key);
7404
+ }
7405
+ return resolver(rawValue);
7406
+ }
7407
+ function resolveStringEnv(key, options) {
7408
+ return resolveEnvValue(key, options, (value) => value);
7409
+ }
7410
+ function resolveBooleanEnv(key, options) {
7411
+ return resolveEnvValue(key, options, (value) => parseBooleanFlag2(value, false));
7412
+ }
7413
+ function resolveListEnv(key, options) {
7414
+ return resolveEnvValue(key, options, (value) => {
7415
+ const separator = options?.separator ?? ",";
7416
+ return value.split(separator).map((entry) => entry.trim()).filter((entry, index, entries) => entry.length > 0 && entries.indexOf(entry) === index);
7417
+ })?.slice();
7418
+ }
7419
+ function resolveJsonEnv(key, options) {
7420
+ return resolveEnvValue(key, options, (value) => {
7421
+ try {
7422
+ return JSON.parse(value);
7423
+ } catch (error) {
7424
+ const message = error instanceof Error ? error.message : String(error);
7425
+ throw new Error(`Generator config env var ${key} must contain valid JSON. ${message}`);
7426
+ }
7427
+ });
7428
+ }
7429
+ function resolveOneOfEnv(key, allowedValues, options) {
7430
+ return resolveEnvValue(key, options, (value) => {
7431
+ if (allowedValues.includes(value)) {
7432
+ return value;
7433
+ }
7434
+ throw new Error(
7435
+ `Generator config env var ${key} must be one of: ${allowedValues.join(", ")}. Received: ${value}.`
7436
+ );
7437
+ });
7438
+ }
7439
+ function generatorEnvString(key, options) {
7440
+ return resolveStringEnv(key, options);
7441
+ }
7442
+ function generatorEnvBoolean(key, options) {
7443
+ return resolveBooleanEnv(key, options);
7444
+ }
7445
+ function generatorEnvList(key, options) {
7446
+ return resolveListEnv(key, options);
7447
+ }
7448
+ function generatorEnvJson(key, options) {
7449
+ return resolveJsonEnv(key, options);
7450
+ }
7451
+ function generatorEnvOneOf(key, allowedValues, options) {
7452
+ return resolveOneOfEnv(key, allowedValues, options);
7453
+ }
7454
+ var generatorEnv = Object.assign(generatorEnvString, {
7455
+ boolean: generatorEnvBoolean,
7456
+ list: generatorEnvList,
7457
+ json: generatorEnvJson,
7458
+ oneOf: generatorEnvOneOf
7459
+ });
7460
+
5310
7461
  // src/generator/postgres-type-mapping.ts
5311
7462
  var NUMBER_TYPES = /* @__PURE__ */ new Set([
5312
7463
  "int2",
@@ -5423,6 +7574,433 @@ function resolvePostgresColumnType(column) {
5423
7574
  return wrapArrayType(baseType, column.arrayDimensions);
5424
7575
  }
5425
7576
 
7577
+ // src/auth/server.ts
7578
+ var DEFAULT_AUTH_BASE_PATH = "/api/auth";
7579
+ var ATHENA_AUTH_BASE_ERROR_CODES = {
7580
+ HANDLER_NOT_CONFIGURED: "HANDLER_NOT_CONFIGURED",
7581
+ INVALID_BASE_URL: "INVALID_BASE_URL",
7582
+ UNTRUSTED_HOST: "UNTRUSTED_HOST"
7583
+ };
7584
+ function capitalize(value) {
7585
+ return value.length > 0 ? `${value[0]?.toUpperCase()}${value.slice(1)}` : value;
7586
+ }
7587
+ function serializeSetCookieValue(name, value, attributes) {
7588
+ const parts = [`${name}=${encodeURIComponent(value)}`];
7589
+ const knownKeys = /* @__PURE__ */ new Set([
7590
+ "maxAge",
7591
+ "expires",
7592
+ "domain",
7593
+ "path",
7594
+ "secure",
7595
+ "httpOnly",
7596
+ "partitioned",
7597
+ "sameSite"
7598
+ ]);
7599
+ if (attributes.maxAge !== void 0) {
7600
+ parts.push(`Max-Age=${Math.trunc(attributes.maxAge)}`);
7601
+ }
7602
+ if (attributes.expires instanceof Date) {
7603
+ parts.push(`Expires=${attributes.expires.toUTCString()}`);
7604
+ }
7605
+ if (attributes.domain) {
7606
+ parts.push(`Domain=${attributes.domain}`);
7607
+ }
7608
+ if (attributes.path) {
7609
+ parts.push(`Path=${attributes.path}`);
7610
+ }
7611
+ if (attributes.secure) {
7612
+ parts.push("Secure");
7613
+ }
7614
+ if (attributes.httpOnly) {
7615
+ parts.push("HttpOnly");
7616
+ }
7617
+ if (attributes.partitioned) {
7618
+ parts.push("Partitioned");
7619
+ }
7620
+ if (attributes.sameSite) {
7621
+ parts.push(`SameSite=${capitalize(attributes.sameSite)}`);
7622
+ }
7623
+ for (const [key, rawValue] of Object.entries(attributes)) {
7624
+ if (knownKeys.has(key) || rawValue === void 0 || rawValue === null || rawValue === false) {
7625
+ continue;
7626
+ }
7627
+ if (rawValue === true) {
7628
+ parts.push(key);
7629
+ continue;
7630
+ }
7631
+ parts.push(`${key}=${String(rawValue)}`);
7632
+ }
7633
+ return parts.join("; ");
7634
+ }
7635
+ function readCookieFromHeaders(headers, name) {
7636
+ const cookieHeader = headers?.get("cookie");
7637
+ if (!cookieHeader) {
7638
+ return void 0;
7639
+ }
7640
+ return parseCookies(cookieHeader).get(name);
7641
+ }
7642
+ function isRecord11(value) {
7643
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
7644
+ }
7645
+ function resolveSessionCandidate(value) {
7646
+ if (!isRecord11(value)) {
7647
+ return null;
7648
+ }
7649
+ const session = isRecord11(value.session) ? value.session : void 0;
7650
+ const user = isRecord11(value.user) ? value.user : void 0;
7651
+ if (session && typeof session.token === "string" && session.token.length > 0 && user) {
7652
+ return {
7653
+ session,
7654
+ user
7655
+ };
7656
+ }
7657
+ return null;
7658
+ }
7659
+ function inferSessionPair(returned) {
7660
+ return resolveSessionCandidate(returned) ?? (isRecord11(returned) ? resolveSessionCandidate(returned.data) : null) ?? (isRecord11(returned) ? resolveSessionCandidate(returned.session) : null);
7661
+ }
7662
+ function resolveResponseHeaders(ctx) {
7663
+ if (ctx.context.responseHeaders instanceof Headers) {
7664
+ return ctx.context.responseHeaders;
7665
+ }
7666
+ const headers = new Headers();
7667
+ ctx.context.responseHeaders = headers;
7668
+ return headers;
7669
+ }
7670
+ function normalizeBaseURL(baseURL) {
7671
+ return baseURL.replace(/\/$/, "");
7672
+ }
7673
+ function normalizeBasePath(basePath) {
7674
+ if (!basePath || basePath === "/") {
7675
+ return DEFAULT_AUTH_BASE_PATH;
7676
+ }
7677
+ const normalized = basePath.startsWith("/") ? basePath : `/${basePath}`;
7678
+ return normalized.endsWith("/") && normalized.length > 1 ? normalized.slice(0, -1) : normalized;
7679
+ }
7680
+ function isDynamicBaseURLConfig2(baseURL) {
7681
+ return typeof baseURL === "object" && baseURL !== null && "allowedHosts" in baseURL && Array.isArray(baseURL.allowedHosts);
7682
+ }
7683
+ function getRequestUrl(request) {
7684
+ try {
7685
+ return new URL(request.url);
7686
+ } catch {
7687
+ return new URL("http://localhost");
7688
+ }
7689
+ }
7690
+ function getRequestHost(request, url) {
7691
+ const forwardedHost = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim();
7692
+ const host = forwardedHost || request.headers.get("host") || url.host;
7693
+ return host || null;
7694
+ }
7695
+ function getRequestProtocol(request, configuredProtocol, url) {
7696
+ if (configuredProtocol === "http" || configuredProtocol === "https") {
7697
+ return configuredProtocol;
7698
+ }
7699
+ const forwardedProto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
7700
+ if (forwardedProto === "http" || forwardedProto === "https") {
7701
+ return forwardedProto;
7702
+ }
7703
+ if (url.protocol === "http:" || url.protocol === "https:") {
7704
+ return url.protocol.slice(0, -1);
7705
+ }
7706
+ return "http";
7707
+ }
7708
+ function resolveRequestBaseURL(baseURL, request) {
7709
+ if (typeof baseURL === "string") {
7710
+ return normalizeBaseURL(baseURL);
7711
+ }
7712
+ const requestUrl = getRequestUrl(request);
7713
+ const host = getRequestHost(request, requestUrl);
7714
+ if (!host) {
7715
+ return null;
7716
+ }
7717
+ if (isDynamicBaseURLConfig2(baseURL)) {
7718
+ const allowedHosts = baseURL.allowedHosts ?? [];
7719
+ if (allowedHosts.length > 0 && !allowedHosts.includes(host)) {
7720
+ return null;
7721
+ }
7722
+ }
7723
+ const protocol = typeof baseURL === "object" && baseURL !== null ? getRequestProtocol(request, baseURL.protocol, requestUrl) : getRequestProtocol(request, void 0, requestUrl);
7724
+ return `${protocol}://${host}`;
7725
+ }
7726
+ function getOrigin(baseURL) {
7727
+ if (!baseURL) {
7728
+ return void 0;
7729
+ }
7730
+ try {
7731
+ return new URL(baseURL).origin;
7732
+ } catch {
7733
+ return void 0;
7734
+ }
7735
+ }
7736
+ async function resolveTrustedOrigins(config, baseURL, request) {
7737
+ const resolved = typeof config.trustedOrigins === "function" ? await config.trustedOrigins(request) : config.trustedOrigins ?? [];
7738
+ const values = [
7739
+ getOrigin(baseURL),
7740
+ ...resolved
7741
+ ];
7742
+ return Array.from(new Set(values.filter((value) => typeof value === "string" && value.length > 0)));
7743
+ }
7744
+ async function resolveTrustedProviders(config, request) {
7745
+ const configured = typeof config.trustedProviders === "function" ? await config.trustedProviders(request) : config.trustedProviders ?? [];
7746
+ const values = [
7747
+ ...Object.keys(config.socialProviders ?? {}),
7748
+ ...configured
7749
+ ];
7750
+ return Array.from(new Set(values.filter((value) => typeof value === "string" && value.length > 0)));
7751
+ }
7752
+ function createJsonResponse(payload, init) {
7753
+ const headers = new Headers(init?.headers);
7754
+ if (!headers.has("content-type")) {
7755
+ headers.set("content-type", "application/json; charset=utf-8");
7756
+ }
7757
+ return new Response(JSON.stringify(payload), {
7758
+ ...init,
7759
+ headers
7760
+ });
7761
+ }
7762
+ function mergeResponseHeaders(response, headers) {
7763
+ return new Response(response.body, {
7764
+ status: response.status,
7765
+ statusText: response.statusText,
7766
+ headers
7767
+ });
7768
+ }
7769
+ function defineAthenaAuthConfig(config) {
7770
+ return config;
7771
+ }
7772
+ function athenaAuth(config) {
7773
+ const normalizedBasePath = normalizeBasePath(config.basePath);
7774
+ const staticBaseURL = typeof config.baseURL === "string" ? normalizeBaseURL(config.baseURL) : void 0;
7775
+ const runtime = {
7776
+ baseURL: staticBaseURL,
7777
+ basePath: normalizedBasePath,
7778
+ secret: config.secret,
7779
+ cookies: {
7780
+ session: config.session,
7781
+ advanced: config.advanced
7782
+ }
7783
+ };
7784
+ const resolvedDatabase = typeof config.database === "function" ? config.database(runtime) : config.database;
7785
+ const cookies = getCookies({
7786
+ baseURL: staticBaseURL ?? config.baseURL,
7787
+ session: config.session,
7788
+ advanced: config.advanced
7789
+ });
7790
+ const auth = {};
7791
+ const createCookieContext = (input = {}) => {
7792
+ const responseHeaders = input.responseHeaders ?? new Headers();
7793
+ const runtimeHeaders = input.headers;
7794
+ const authCookies = input.cookies ?? auth.cookies;
7795
+ const setCookie = input.setCookie ?? ((name, value, attributes) => {
7796
+ responseHeaders.append(
7797
+ "set-cookie",
7798
+ serializeSetCookieValue(name, value, attributes)
7799
+ );
7800
+ });
7801
+ return {
7802
+ headers: runtimeHeaders,
7803
+ getCookie: input.getCookie ?? ((name) => readCookieFromHeaders(runtimeHeaders, name)),
7804
+ setCookie,
7805
+ logger: input.logger,
7806
+ setSignedCookie: input.setSignedCookie,
7807
+ getSignedCookie: input.getSignedCookie,
7808
+ context: {
7809
+ secret: runtime.secret,
7810
+ authCookies,
7811
+ sessionConfig: {
7812
+ expiresIn: config.session?.expiresIn
7813
+ },
7814
+ options: {
7815
+ session: {
7816
+ cookieCache: config.session?.cookieCache
7817
+ },
7818
+ account: {
7819
+ storeAccountCookie: true
7820
+ }
7821
+ },
7822
+ setNewSession: input.setNewSession
7823
+ }
7824
+ };
7825
+ };
7826
+ const setSession = async (input, session, dontRememberMe, overrides) => {
7827
+ const cookieContext = createCookieContext(input);
7828
+ await setSessionCookie(cookieContext, session, dontRememberMe, overrides);
7829
+ };
7830
+ const clearSession = (input, skipDontRememberMe) => {
7831
+ const cookieContext = createCookieContext(input);
7832
+ deleteSessionCookie(cookieContext, skipDontRememberMe);
7833
+ };
7834
+ const applyResponseCookies = async (ctx) => {
7835
+ const responseHeaders = resolveResponseHeaders(ctx);
7836
+ const session = ctx.context.setSession ?? inferSessionPair(ctx.context.returned);
7837
+ if (ctx.context.clearSession) {
7838
+ clearSession({
7839
+ headers: ctx.headers,
7840
+ responseHeaders
7841
+ });
7842
+ }
7843
+ if (session) {
7844
+ await setSession(
7845
+ {
7846
+ headers: ctx.headers,
7847
+ responseHeaders
7848
+ },
7849
+ session,
7850
+ ctx.context.dontRememberMe,
7851
+ ctx.context.cookieOverrides
7852
+ );
7853
+ }
7854
+ return responseHeaders;
7855
+ };
7856
+ const runAfterHooks = async (ctx) => {
7857
+ for (const plugin of auth.plugins) {
7858
+ for (const hook of plugin.hooks?.after ?? []) {
7859
+ if (!hook.matcher(ctx)) {
7860
+ continue;
7861
+ }
7862
+ await hook.handler({
7863
+ ...ctx,
7864
+ auth
7865
+ });
7866
+ }
7867
+ }
7868
+ return ctx;
7869
+ };
7870
+ const resolveRequestContext = async (request) => {
7871
+ const requestUrl = getRequestUrl(request);
7872
+ const resolvedBaseURL = resolveRequestBaseURL(config.baseURL, request);
7873
+ if (!resolvedBaseURL) {
7874
+ throw new Error(
7875
+ isDynamicBaseURLConfig2(config.baseURL) ? "Could not resolve base URL from request. Check allowedHosts/baseURL." : "Could not resolve base URL from request."
7876
+ );
7877
+ }
7878
+ const requestCookies = getCookies({
7879
+ baseURL: resolvedBaseURL,
7880
+ session: config.session,
7881
+ advanced: config.advanced
7882
+ });
7883
+ const trustedOrigins = await resolveTrustedOrigins(config, resolvedBaseURL, request);
7884
+ const trustedProviders = await resolveTrustedProviders(config, request);
7885
+ return {
7886
+ auth,
7887
+ request,
7888
+ url: requestUrl,
7889
+ path: requestUrl.pathname,
7890
+ basePath: normalizedBasePath,
7891
+ baseURL: resolvedBaseURL,
7892
+ origin: getOrigin(resolvedBaseURL) ?? resolvedBaseURL,
7893
+ headers: request.headers,
7894
+ cookies: requestCookies,
7895
+ trustedOrigins,
7896
+ trustedProviders,
7897
+ options: config,
7898
+ runtime: {
7899
+ ...runtime,
7900
+ baseURL: resolvedBaseURL
7901
+ },
7902
+ database: auth.database,
7903
+ socialProviders: auth.socialProviders
7904
+ };
7905
+ };
7906
+ const handler = async (request) => {
7907
+ const requestContext = await resolveRequestContext(request);
7908
+ if (typeof config.handler !== "function") {
7909
+ return createJsonResponse(
7910
+ {
7911
+ ok: false,
7912
+ code: ATHENA_AUTH_BASE_ERROR_CODES.HANDLER_NOT_CONFIGURED,
7913
+ error: "No native auth handler was configured for this Athena auth instance.",
7914
+ path: requestContext.path,
7915
+ basePath: requestContext.basePath
7916
+ },
7917
+ { status: 501 }
7918
+ );
7919
+ }
7920
+ const result = await config.handler(requestContext);
7921
+ if (result instanceof Response) {
7922
+ return result;
7923
+ }
7924
+ const response = result.response ?? (result.returned !== void 0 ? createJsonResponse(result.returned) : new Response(null, { status: 204 }));
7925
+ const responseHeaders = new Headers(response.headers);
7926
+ await runAfterHooks({
7927
+ path: requestContext.path,
7928
+ headers: request.headers,
7929
+ context: {
7930
+ responseHeaders,
7931
+ returned: result.returned,
7932
+ setSession: result.setSession,
7933
+ clearSession: result.clearSession,
7934
+ dontRememberMe: result.dontRememberMe,
7935
+ cookieOverrides: result.cookieOverrides
7936
+ }
7937
+ });
7938
+ return mergeResponseHeaders(response, responseHeaders);
7939
+ };
7940
+ const api = Object.assign(
7941
+ {
7942
+ applyResponseCookies,
7943
+ clearSession,
7944
+ createCookieContext,
7945
+ getCookieCache,
7946
+ getSessionCookie,
7947
+ resolveRequestContext,
7948
+ runAfterHooks,
7949
+ setSession
7950
+ },
7951
+ config.api ?? {}
7952
+ );
7953
+ const $ERROR_CODES = {
7954
+ ...auth.plugins?.reduce((acc, plugin) => {
7955
+ if (plugin.$ERROR_CODES) {
7956
+ return {
7957
+ ...acc,
7958
+ ...plugin.$ERROR_CODES
7959
+ };
7960
+ }
7961
+ return acc;
7962
+ }, {}),
7963
+ ...config.errorCodes ?? {},
7964
+ ...ATHENA_AUTH_BASE_ERROR_CODES
7965
+ };
7966
+ Object.assign(auth, {
7967
+ config,
7968
+ options: config,
7969
+ runtime,
7970
+ database: resolvedDatabase,
7971
+ socialProviders: config.socialProviders ?? {},
7972
+ plugins: [...config.plugins ?? []],
7973
+ cookies,
7974
+ api,
7975
+ $ERROR_CODES,
7976
+ createCookieContext,
7977
+ setSession,
7978
+ clearSession,
7979
+ applyResponseCookies,
7980
+ runAfterHooks,
7981
+ resolveRequestContext,
7982
+ handler
7983
+ });
7984
+ auth.$context = Promise.all([
7985
+ resolveTrustedOrigins(config, staticBaseURL),
7986
+ resolveTrustedProviders(config)
7987
+ ]).then(([trustedOrigins, trustedProviders]) => ({
7988
+ auth,
7989
+ options: config,
7990
+ runtime,
7991
+ basePath: normalizedBasePath,
7992
+ baseURL: staticBaseURL,
7993
+ origin: getOrigin(staticBaseURL),
7994
+ database: auth.database,
7995
+ socialProviders: auth.socialProviders,
7996
+ plugins: auth.plugins,
7997
+ cookies: auth.cookies,
7998
+ trustedOrigins,
7999
+ trustedProviders
8000
+ }));
8001
+ return auth;
8002
+ }
8003
+
5426
8004
  // src/browser.ts
5427
8005
  function throwBrowserUnsupported(apiName) {
5428
8006
  throw new Error(
@@ -5454,6 +8032,6 @@ async function runSchemaGenerator(options = {}) {
5454
8032
  return throwBrowserUnsupported("runSchemaGenerator");
5455
8033
  }
5456
8034
 
5457
- export { AthenaClient, AthenaError, AthenaErrorCategory, AthenaErrorCode, AthenaErrorKind, AthenaGatewayError, Backend, DEFAULT_POSTGRES_SCHEMAS, assertInt, coerceInt, createAuthClient, createAuthReactEmailInput, createClient, createModelFormAdapter, createPostgresIntrospectionProvider, createTypedClient, defineAuthEmailTemplate, defineDatabase, defineGeneratorConfig, defineModel, defineRegistry, defineSchema, findGeneratorConfigPath, generateArtifactsFromSnapshot, identifier, isAthenaGatewayError, isOk, loadGeneratorConfig, normalizeAthenaError, normalizeAthenaGatewayBaseUrl, normalizeGeneratorConfig, normalizeSchemaSelection, parseBooleanFlag2 as parseBooleanFlag, renderAthenaReactEmail, requireAffected, requireSuccess, resolveGeneratorProvider, resolvePostgresColumnType, resolveProviderSchemas, runSchemaGenerator, toModelFormDefaults, toModelPayload, unwrap, unwrapOne, unwrapRows, verifyAthenaGatewayUrl, withRetry };
8035
+ export { ATHENA_AUTH_BASE_ERROR_CODES, AthenaClient, AthenaError, AthenaErrorCategory, AthenaErrorCode, AthenaErrorKind, AthenaGatewayError, AthenaStorageError, AthenaStorageErrorCode, Backend, DEFAULT_POSTGRES_SCHEMAS, assertInt, athenaAuth, coerceInt, createAthenaStorageError, createAuthClient, createAuthReactEmailInput, createClient, createModelFormAdapter, createPostgresIntrospectionProvider, createTypedClient, defineAthenaAuthConfig, defineAuthEmailTemplate, defineDatabase, defineGeneratorConfig, defineModel, defineRegistry, defineSchema, findGeneratorConfigPath, generateArtifactsFromSnapshot, generatorEnv, identifier, isAthenaGatewayError, isOk, loadGeneratorConfig, normalizeAthenaError, normalizeAthenaGatewayBaseUrl, normalizeGeneratorConfig, normalizeSchemaSelection, parseBooleanFlag2 as parseBooleanFlag, renderAthenaReactEmail, requireAffected, requireSuccess, resolveGeneratorProvider, resolvePostgresColumnType, resolveProviderSchemas, runSchemaGenerator, storageSdkManifest, toModelFormDefaults, toModelPayload, unwrap, unwrapOne, unwrapRows, verifyAthenaGatewayUrl, withRetry };
5458
8036
  //# sourceMappingURL=browser.js.map
5459
8037
  //# sourceMappingURL=browser.js.map