ts-ag 1.2.0 → 1.2.2

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.
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  import { parse, stringify } from "devalue";
2
- import * as v from "valibot";
3
- import { parse as parse$1 } from "cookie";
2
+ import { parse as parse$1, parseAsync } from "valibot";
3
+ import { parse as parse$2 } from "cookie-es";
4
4
  import { Result, ResultAsync } from "neverthrow";
5
- import { AdminGetUserCommand, AdminInitiateAuthCommand, AdminListGroupsForUserCommand, ChangePasswordCommand, CognitoIdentityProviderClient, ConfirmForgotPasswordCommand, ConfirmSignUpCommand, ForgotPasswordCommand, GlobalSignOutCommand, RespondToAuthChallengeCommand, SignUpCommand } from "@aws-sdk/client-cognito-identity-provider";
5
+ import { AdminGetUserCommand, AdminInitiateAuthCommand, AdminListGroupsForUserCommand, ChangePasswordCommand, CognitoIdentityProviderClient, ConfirmForgotPasswordCommand, ConfirmSignUpCommand, ForgotPasswordCommand, GetTokensFromRefreshTokenCommand, GlobalSignOutCommand, RespondToAuthChallengeCommand, SignUpCommand } from "@aws-sdk/client-cognito-identity-provider";
6
6
  import { createHmac } from "node:crypto";
7
7
  import { GetObjectCommand, HeadObjectCommand, S3Client } from "@aws-sdk/client-s3";
8
8
  import { getSignedUrl as getSignedUrl$1 } from "@aws-sdk/s3-request-presigner";
@@ -33,8 +33,8 @@ const bodyMethods = [
33
33
  ];
34
34
  const queryMethods = ["GET", "DELETE"];
35
35
  async function _apiRequest(path, method, input, schema, environment, apiUrl, headers) {
36
- if (schema) if (schema.async === true) await v.parseAsync(schema, input);
37
- else v.parse(schema, input);
36
+ if (schema) if (schema.async === true) await parseAsync(schema, input);
37
+ else parse$1(schema, input);
38
38
  let url = `${apiUrl}${apiUrl.endsWith("/") ? "" : "/"}${path}`;
39
39
  if (queryMethods.includes(method)) {
40
40
  const params = new URLSearchParams();
@@ -116,36 +116,48 @@ function wrapHandler(handler) {
116
116
  * The separation means that they can be returned from functions that are certainly run inside a lambda fucntion but theyre not the actual return of the lambda.
117
117
  * Im not sure it this is optimal behaviour and if not we will migrate to only using the errorResponse function
118
118
  */
119
- const error_lambda_badRequest = (message, fieldName, fieldValue) => ({
120
- type: "badRequest",
121
- message,
122
- fieldName,
123
- fieldValue
124
- });
125
- const error_lambda_unauthorized = (message) => ({
126
- type: "unauthorized",
127
- message
128
- });
129
- const error_lambda_forbidden = (message) => ({
130
- type: "forbidden",
131
- message
132
- });
133
- const error_lambda_notFound = (message, fieldName, fieldValue) => ({
134
- type: "notFound",
135
- message,
136
- fieldName,
137
- fieldValue
138
- });
139
- const error_lambda_conflict = (message, fieldName, fieldValue) => ({
140
- type: "conflict",
141
- message,
142
- fieldName,
143
- fieldValue
144
- });
145
- const error_lambda_internal = (message) => ({
146
- type: "internal",
147
- message
148
- });
119
+ function error_lambda_badRequest(message, fieldName, fieldValue) {
120
+ return {
121
+ type: "badRequest",
122
+ message,
123
+ fieldName,
124
+ fieldValue
125
+ };
126
+ }
127
+ function error_lambda_unauthorized(message) {
128
+ return {
129
+ type: "unauthorized",
130
+ message
131
+ };
132
+ }
133
+ function error_lambda_forbidden(message) {
134
+ return {
135
+ type: "forbidden",
136
+ message
137
+ };
138
+ }
139
+ function error_lambda_notFound(message, fieldName, fieldValue) {
140
+ return {
141
+ type: "notFound",
142
+ message,
143
+ fieldName,
144
+ fieldValue
145
+ };
146
+ }
147
+ function error_lambda_conflict(message, fieldName, fieldValue) {
148
+ return {
149
+ type: "conflict",
150
+ message,
151
+ fieldName,
152
+ fieldValue
153
+ };
154
+ }
155
+ function error_lambda_internal(message) {
156
+ return {
157
+ type: "internal",
158
+ message
159
+ };
160
+ }
149
161
  //#endregion
150
162
  //#region src/lambda/response.ts
151
163
  function field(obj) {
@@ -246,15 +258,17 @@ function response_ok(body, headers, cookies) {
246
258
  /**
247
259
  * Wraps cookies parse along with the api gateway event with neverthrow
248
260
  */
249
- const getCookies = Result.fromThrowable((event) => {
250
- if (!("headers" in event) || !event.headers) throw new Error("No headers in event");
251
- const cookieString = Array.isArray(event.cookies) && event.cookies.length > 0 ? event.cookies.join("; ") : event.headers.Cookie || event.headers.cookie;
252
- if (!cookieString) throw new Error("No cookies found in event");
253
- return parse$1(cookieString);
254
- }, (e) => {
255
- if (e instanceof Error) return error_lambda_unauthorized(e.message);
256
- return error_lambda_unauthorized("Invalid Cookies");
257
- });
261
+ function getCookies(event) {
262
+ return Result.fromThrowable(() => {
263
+ if (!("headers" in event) || !event.headers) throw new Error("No headers in event");
264
+ const cookieString = Array.isArray(event.cookies) && event.cookies.length > 0 ? event.cookies.join("; ") : event.headers.Cookie || event.headers.cookie;
265
+ if (!cookieString) throw new Error("No cookies found in event");
266
+ return parse$2(cookieString);
267
+ }, (e) => {
268
+ if (e instanceof Error) return error_lambda_unauthorized(e.message);
269
+ return error_lambda_unauthorized("Invalid Cookies");
270
+ })();
271
+ }
258
272
  //#endregion
259
273
  //#region src/cognito/client.ts
260
274
  /**
@@ -449,20 +463,22 @@ function isRecord$2(value) {
449
463
  /**
450
464
  * Performs an AdminGetUserCommand and extracts the user attributes into an object
451
465
  */
452
- const getUserDetails = ResultAsync.fromThrowable(async (a) => {
453
- console.log("getUserDetails: Getting details for user: ", a.username);
454
- const res = await getCognitoClient().send(new AdminGetUserCommand({
455
- UserPoolId: a.userPoolId,
456
- Username: a.username
457
- }));
458
- return {
459
- ...res,
460
- UserAttributes: extractAttributes(res.UserAttributes)
461
- };
462
- }, (e) => {
463
- console.error("getUserDetails:error:", e);
464
- return error_cognito(e);
465
- });
466
+ function getUserDetails(a) {
467
+ return ResultAsync.fromThrowable(async () => {
468
+ console.log("getUserDetails: Getting details for user: ", a.username);
469
+ const res = await getCognitoClient().send(new AdminGetUserCommand({
470
+ UserPoolId: a.userPoolId,
471
+ Username: a.username
472
+ }));
473
+ return {
474
+ ...res,
475
+ UserAttributes: extractAttributes(res.UserAttributes)
476
+ };
477
+ }, (e) => {
478
+ console.error("getUserDetails:error:", e);
479
+ return error_cognito(e);
480
+ })();
481
+ }
466
482
  /**
467
483
  * @returns An object of attributes with their names as keys and values as values.
468
484
  */
@@ -476,16 +492,18 @@ function extractAttributes(attrs) {
476
492
  /**
477
493
  * Performs an AdminGetUserCommand and extracts the user attributes into an object
478
494
  */
479
- const getUserGroups = ResultAsync.fromThrowable(async (a) => {
480
- console.log("getUserGroups: Getting groups for user: ", a.username);
481
- return await getCognitoClient().send(new AdminListGroupsForUserCommand({
482
- UserPoolId: a.userPoolId,
483
- Username: a.username
484
- }));
485
- }, (e) => {
486
- console.error("getUserGroups:error:", e);
487
- return error_cognito(e);
488
- });
495
+ function getUserGroups(a) {
496
+ return ResultAsync.fromThrowable(async () => {
497
+ console.log("getUserGroups: Getting groups for user: ", a.username);
498
+ return await getCognitoClient().send(new AdminListGroupsForUserCommand({
499
+ UserPoolId: a.userPoolId,
500
+ Username: a.username
501
+ }));
502
+ }, (e) => {
503
+ console.error("getUserGroups:error:", e);
504
+ return error_cognito(e);
505
+ })();
506
+ }
489
507
  //#endregion
490
508
  //#region src/cognito/password.ts
491
509
  /**
@@ -506,16 +524,18 @@ function computeSecretHash(username, clientId, clientSecret) {
506
524
  * @param oldPassword - Current password.
507
525
  * @param newPassword - New password to set.
508
526
  */
509
- const changePassword = ResultAsync.fromThrowable(async (accessToken, oldPassword, newPassword) => {
510
- return getCognitoClient().send(new ChangePasswordCommand({
511
- AccessToken: accessToken,
512
- PreviousPassword: oldPassword,
513
- ProposedPassword: newPassword
514
- }));
515
- }, (e) => {
516
- console.error("ChangePasswordCommand error", e);
517
- return error_cognito(e);
518
- });
527
+ function changePassword(accessToken, oldPassword, newPassword) {
528
+ return ResultAsync.fromThrowable(async () => {
529
+ return getCognitoClient().send(new ChangePasswordCommand({
530
+ AccessToken: accessToken,
531
+ PreviousPassword: oldPassword,
532
+ ProposedPassword: newPassword
533
+ }));
534
+ }, (e) => {
535
+ console.error("ChangePasswordCommand error", e);
536
+ return error_cognito(e);
537
+ })();
538
+ }
519
539
  /**
520
540
  * Completes a forgot-password flow by submitting the confirmation code and new password.
521
541
  *
@@ -525,18 +545,20 @@ const changePassword = ResultAsync.fromThrowable(async (accessToken, oldPassword
525
545
  * @param a.clientId - Cognito app client ID.
526
546
  * @param a.clientSecret - Cognito app client secret.
527
547
  */
528
- const confirmForgotPassword = ResultAsync.fromThrowable((a) => {
529
- return getCognitoClient().send(new ConfirmForgotPasswordCommand({
530
- ClientId: a.clientId,
531
- Username: a.username,
532
- ConfirmationCode: a.confirmationCode,
533
- Password: a.newPassword,
534
- SecretHash: computeSecretHash(a.username, a.clientId, a.clientSecret)
535
- }));
536
- }, (e) => {
537
- console.error("ConfirmForgotPasswordCommand error", e);
538
- return error_cognito(e);
539
- });
548
+ function confirmForgotPassword(a) {
549
+ return ResultAsync.fromThrowable(() => {
550
+ return getCognitoClient().send(new ConfirmForgotPasswordCommand({
551
+ ClientId: a.clientId,
552
+ Username: a.username,
553
+ ConfirmationCode: a.confirmationCode,
554
+ Password: a.newPassword,
555
+ SecretHash: computeSecretHash(a.username, a.clientId, a.clientSecret)
556
+ }));
557
+ }, (e) => {
558
+ console.error("ConfirmForgotPasswordCommand error", e);
559
+ return error_cognito(e);
560
+ })();
561
+ }
540
562
  /**
541
563
  * Confirms a user's signup using the confirmation code sent by Cognito.
542
564
  *
@@ -545,17 +567,19 @@ const confirmForgotPassword = ResultAsync.fromThrowable((a) => {
545
567
  * @param a.clientId - Cognito app client ID.
546
568
  * @param a.clientSecret - Cognito app client secret.
547
569
  */
548
- const confirmSignup = ResultAsync.fromThrowable((a) => {
549
- return getCognitoClient().send(new ConfirmSignUpCommand({
550
- ClientId: a.clientId,
551
- Username: a.username,
552
- ConfirmationCode: a.confirmationCode,
553
- SecretHash: computeSecretHash(a.username, a.clientId, a.clientSecret)
554
- }));
555
- }, (e) => {
556
- console.error("ConfirmSignUpCommand error", e);
557
- return error_cognito(e);
558
- });
570
+ function confirmSignup(a) {
571
+ return ResultAsync.fromThrowable(() => {
572
+ return getCognitoClient().send(new ConfirmSignUpCommand({
573
+ ClientId: a.clientId,
574
+ Username: a.username,
575
+ ConfirmationCode: a.confirmationCode,
576
+ SecretHash: computeSecretHash(a.username, a.clientId, a.clientSecret)
577
+ }));
578
+ }, (e) => {
579
+ console.error("ConfirmSignUpCommand error", e);
580
+ return error_cognito(e);
581
+ })();
582
+ }
559
583
  /**
560
584
  * Starts a forgot-password flow by sending a reset code to the user.
561
585
  *
@@ -563,16 +587,18 @@ const confirmSignup = ResultAsync.fromThrowable((a) => {
563
587
  * @param a.clientId - Cognito app client ID.
564
588
  * @param a.clientSecret - Cognito app client secret.
565
589
  */
566
- const forgotPassword = ResultAsync.fromThrowable((a) => {
567
- return getCognitoClient().send(new ForgotPasswordCommand({
568
- ClientId: a.clientId,
569
- Username: a.username,
570
- SecretHash: computeSecretHash(a.username, a.clientId, a.clientSecret)
571
- }));
572
- }, (e) => {
573
- console.error("ForgotPasswordCommand error", e);
574
- return error_cognito(e);
575
- });
590
+ function forgotPassword(a) {
591
+ return ResultAsync.fromThrowable(() => {
592
+ return getCognitoClient().send(new ForgotPasswordCommand({
593
+ ClientId: a.clientId,
594
+ Username: a.username,
595
+ SecretHash: computeSecretHash(a.username, a.clientId, a.clientSecret)
596
+ }));
597
+ }, (e) => {
598
+ console.error("ForgotPasswordCommand error", e);
599
+ return error_cognito(e);
600
+ })();
601
+ }
576
602
  /**
577
603
  * Signs a user in with ADMIN_USER_PASSWORD_AUTH.
578
604
  *
@@ -582,21 +608,34 @@ const forgotPassword = ResultAsync.fromThrowable((a) => {
582
608
  * @param a.clientSecret - Cognito app client secret.
583
609
  * @param a.userPoolId - Cognito user pool ID.
584
610
  */
585
- const login = ResultAsync.fromThrowable((a) => {
586
- return getCognitoClient().send(new AdminInitiateAuthCommand({
587
- AuthFlow: "ADMIN_USER_PASSWORD_AUTH",
588
- ClientId: a.clientId,
589
- UserPoolId: a.userPoolId,
590
- AuthParameters: {
591
- USERNAME: a.username,
592
- PASSWORD: a.password,
593
- SECRET_HASH: computeSecretHash(a.username, a.clientId, a.clientSecret)
594
- }
595
- }));
596
- }, (e) => {
597
- console.error("AdminInitiateAuthCommand error", e);
598
- return error_cognito(e);
599
- });
611
+ function login(a) {
612
+ return ResultAsync.fromThrowable(() => {
613
+ return getCognitoClient().send(new AdminInitiateAuthCommand({
614
+ AuthFlow: "ADMIN_USER_PASSWORD_AUTH",
615
+ ClientId: a.clientId,
616
+ UserPoolId: a.userPoolId,
617
+ AuthParameters: {
618
+ USERNAME: a.username,
619
+ PASSWORD: a.password,
620
+ SECRET_HASH: computeSecretHash(a.username, a.clientId, a.clientSecret)
621
+ }
622
+ }));
623
+ }, (e) => {
624
+ console.error("AdminInitiateAuthCommand error", e);
625
+ return error_cognito(e);
626
+ })();
627
+ }
628
+ /**
629
+ * Sends a GetTokensFromRefreshTokenCommand
630
+ */
631
+ function refreshTokens(a) {
632
+ return ResultAsync.fromThrowable(() => {
633
+ return getCognitoClient().send(new GetTokensFromRefreshTokenCommand(a));
634
+ }, (e) => {
635
+ console.error("refreshTokens: GetTokensFromRefreshTokenCommand error", e);
636
+ return error_cognito(e);
637
+ })();
638
+ }
600
639
  /**
601
640
  * Exchanges a refresh token for new tokens.
602
641
  *
@@ -606,31 +645,35 @@ const login = ResultAsync.fromThrowable((a) => {
606
645
  * @param a.clientSecret - Cognito app client secret.
607
646
  * @param a.userPoolId - Cognito user pool ID.
608
647
  */
609
- const refreshTokens = ResultAsync.fromThrowable((a) => {
610
- return getCognitoClient().send(new AdminInitiateAuthCommand({
611
- AuthFlow: "REFRESH_TOKEN_AUTH",
612
- ClientId: a.clientId,
613
- UserPoolId: a.userPoolId,
614
- AuthParameters: {
615
- REFRESH_TOKEN: a.refreshToken,
616
- SECRET_HASH: computeSecretHash(a.username, a.clientId, a.clientSecret)
617
- }
618
- }));
619
- }, (e) => {
620
- console.error("refreshTokens: AdminInitiateAuthCommand error", e);
621
- return error_cognito(e);
622
- });
648
+ function refreshTokensAuth(a) {
649
+ return ResultAsync.fromThrowable(() => {
650
+ return getCognitoClient().send(new AdminInitiateAuthCommand({
651
+ AuthFlow: "REFRESH_TOKEN_AUTH",
652
+ ClientId: a.clientId,
653
+ UserPoolId: a.userPoolId,
654
+ AuthParameters: {
655
+ REFRESH_TOKEN: a.refreshToken,
656
+ SECRET_HASH: computeSecretHash(a.username, a.clientId, a.clientSecret)
657
+ }
658
+ }));
659
+ }, (e) => {
660
+ console.error("refreshTokens: AdminInitiateAuthCommand error", e);
661
+ return error_cognito(e);
662
+ })();
663
+ }
623
664
  /**
624
665
  * Globally signs out a user by invalidating all refresh tokens.
625
666
  *
626
667
  * @param accessToken - Access token for the authenticated user.
627
668
  */
628
- const logout = ResultAsync.fromThrowable((accessToken) => {
629
- return getCognitoClient().send(new GlobalSignOutCommand({ AccessToken: accessToken }));
630
- }, (e) => {
631
- console.error("GlobalSignOutCommand error", e);
632
- return error_cognito(e);
633
- });
669
+ function logout(accessToken) {
670
+ return ResultAsync.fromThrowable(() => {
671
+ return getCognitoClient().send(new GlobalSignOutCommand({ AccessToken: accessToken }));
672
+ }, (e) => {
673
+ console.error("GlobalSignOutCommand error", e);
674
+ return error_cognito(e);
675
+ })();
676
+ }
634
677
  /**
635
678
  * Completes a NEW_PASSWORD_REQUIRED challenge for users who must set a new password.
636
679
  *
@@ -640,21 +683,23 @@ const logout = ResultAsync.fromThrowable((accessToken) => {
640
683
  * @param a.clientId - Cognito app client ID.
641
684
  * @param a.clientSecret - Cognito app client secret.
642
685
  */
643
- const resetPassword = ResultAsync.fromThrowable((a) => {
644
- return getCognitoClient().send(new RespondToAuthChallengeCommand({
645
- ChallengeName: "NEW_PASSWORD_REQUIRED",
646
- ClientId: a.clientId,
647
- Session: a.session,
648
- ChallengeResponses: {
649
- SECRET_HASH: computeSecretHash(a.username, a.clientId, a.clientSecret),
650
- NEW_PASSWORD: a.newPassword,
651
- USERNAME: a.username
652
- }
653
- }));
654
- }, (e) => {
655
- console.error("RespondToAuthChallengeCommand error", e);
656
- return error_cognito(e);
657
- });
686
+ function resetPassword(a) {
687
+ return ResultAsync.fromThrowable(() => {
688
+ return getCognitoClient().send(new RespondToAuthChallengeCommand({
689
+ ChallengeName: "NEW_PASSWORD_REQUIRED",
690
+ ClientId: a.clientId,
691
+ Session: a.session,
692
+ ChallengeResponses: {
693
+ SECRET_HASH: computeSecretHash(a.username, a.clientId, a.clientSecret),
694
+ NEW_PASSWORD: a.newPassword,
695
+ USERNAME: a.username
696
+ }
697
+ }));
698
+ }, (e) => {
699
+ console.error("RespondToAuthChallengeCommand error", e);
700
+ return error_cognito(e);
701
+ })();
702
+ }
658
703
  /**
659
704
  * Registers a new user with Cognito and optional custom attributes.
660
705
  *
@@ -664,28 +709,30 @@ const resetPassword = ResultAsync.fromThrowable((a) => {
664
709
  * @param a.clientSecret - Cognito app client secret.
665
710
  * @param a.<attribute> - Any additional user attributes to set.
666
711
  */
667
- const signUp = ResultAsync.fromThrowable((a) => {
668
- const cognitoClient = getCognitoClient();
669
- const secretHash = computeSecretHash(a.username, a.clientId, a.clientSecret);
670
- return cognitoClient.send(new SignUpCommand({
671
- ClientId: a.clientId,
672
- Username: a.username,
673
- Password: a.password,
674
- SecretHash: secretHash,
675
- UserAttributes: Object.entries(a).filter(([key]) => ![
676
- "username",
677
- "password",
678
- "clientId",
679
- "clientSecret"
680
- ].includes(key)).map(([key, value]) => ({
681
- Name: key,
682
- Value: value
683
- }))
684
- }));
685
- }, (e) => {
686
- console.error("SignUpCommand error", e);
687
- return error_cognito(e);
688
- });
712
+ function signUp(a) {
713
+ return ResultAsync.fromThrowable(() => {
714
+ const cognitoClient = getCognitoClient();
715
+ const secretHash = computeSecretHash(a.username, a.clientId, a.clientSecret);
716
+ return cognitoClient.send(new SignUpCommand({
717
+ ClientId: a.clientId,
718
+ Username: a.username,
719
+ Password: a.password,
720
+ SecretHash: secretHash,
721
+ UserAttributes: Object.entries(a).filter(([key]) => ![
722
+ "username",
723
+ "password",
724
+ "clientId",
725
+ "clientSecret"
726
+ ].includes(key)).map(([key, value]) => ({
727
+ Name: key,
728
+ Value: value
729
+ }))
730
+ }));
731
+ }, (e) => {
732
+ console.error("SignUpCommand error", e);
733
+ return error_cognito(e);
734
+ })();
735
+ }
689
736
  /**
690
737
  * Exchanges an OAuth2 authorization code for Cognito tokens using the token endpoint.
691
738
  * See https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html for request/response fields and grant details.
@@ -697,30 +744,32 @@ const signUp = ResultAsync.fromThrowable((a) => {
697
744
  * @param a.cognitoDomain - Cognito domain URL (e.g., your-domain.auth.region.amazoncognito.com).
698
745
  * @returns Parsed token payload containing `access_token`, `id_token`, `refresh_token`, token type, and expiry.
699
746
  */
700
- const verifyOAuthToken = ResultAsync.fromThrowable(async (a) => {
701
- const basicAuth = Buffer.from(`${a.clientId}:${a.clientSecret}`).toString("base64");
702
- const params = new URLSearchParams();
703
- params.append("grant_type", "authorization_code");
704
- params.append("code", a.code);
705
- params.append("redirect_uri", a.redirectUri);
706
- console.log("verifyOAuthToken: params", params.toString());
707
- const tokenRes = await fetch(`https://${a.cognitoDomain}/oauth2/token`, {
708
- method: "POST",
709
- headers: {
710
- "Content-Type": "application/x-www-form-urlencoded",
711
- Authorization: `Basic ${basicAuth}`
712
- },
713
- body: params.toString()
714
- });
715
- if (!tokenRes.ok) {
716
- console.error("verifyOAuthToken: token exchange failed", await tokenRes.text());
717
- throw Object.assign(/* @__PURE__ */ new Error("OAuth token exchange failed"), { name: "NotAuthorizedException" });
718
- }
719
- return await tokenRes.json();
720
- }, (e) => {
721
- console.error("verifyOAuthToken:error", e);
722
- return error_cognito(e);
723
- });
747
+ function verifyOAuthToken(a) {
748
+ return ResultAsync.fromThrowable(async () => {
749
+ const basicAuth = Buffer.from(`${a.clientId}:${a.clientSecret}`).toString("base64");
750
+ const params = new URLSearchParams();
751
+ params.append("grant_type", "authorization_code");
752
+ params.append("code", a.code);
753
+ params.append("redirect_uri", a.redirectUri);
754
+ console.log("verifyOAuthToken: params", params.toString());
755
+ const tokenRes = await fetch(`https://${a.cognitoDomain}/oauth2/token`, {
756
+ method: "POST",
757
+ headers: {
758
+ "Content-Type": "application/x-www-form-urlencoded",
759
+ Authorization: `Basic ${basicAuth}`
760
+ },
761
+ body: params.toString()
762
+ });
763
+ if (!tokenRes.ok) {
764
+ console.error("verifyOAuthToken: token exchange failed", await tokenRes.text());
765
+ throw Object.assign(/* @__PURE__ */ new Error("OAuth token exchange failed"), { name: "NotAuthorizedException" });
766
+ }
767
+ return await tokenRes.json();
768
+ }, (e) => {
769
+ console.error("verifyOAuthToken:error", e);
770
+ return error_cognito(e);
771
+ })();
772
+ }
724
773
  /**
725
774
  * Exchanges an OAuth2 refresh token for Cognito tokens using the oauth token endpoint.
726
775
  * See https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html for request/response fields and grant details.
@@ -731,29 +780,31 @@ const verifyOAuthToken = ResultAsync.fromThrowable(async (a) => {
731
780
  * @param a.cognitoDomain - Cognito domain URL (e.g., your-domain.auth.region.amazoncognito.com).
732
781
  * @returns Parsed token payload containing `access_token`, `id_token`, `refresh_token`, token type, and expiry.
733
782
  */
734
- const refreshOAuthToken = ResultAsync.fromThrowable(async (a) => {
735
- const basicAuth = Buffer.from(`${a.clientId}:${a.clientSecret}`).toString("base64");
736
- const params = new URLSearchParams();
737
- params.append("grant_type", "refresh_token");
738
- params.append("refresh_token", a.refreshToken);
739
- console.log("refreshOAuthToken: params", params.toString());
740
- const tokenRes = await fetch(`https://${a.cognitoDomain}/oauth2/token`, {
741
- method: "POST",
742
- headers: {
743
- "Content-Type": "application/x-www-form-urlencoded",
744
- Authorization: `Basic ${basicAuth}`
745
- },
746
- body: params.toString()
747
- });
748
- if (!tokenRes.ok) {
749
- console.error("refreshOAuthToken: token exchange failed", await tokenRes.text());
750
- throw Object.assign(/* @__PURE__ */ new Error("OAuth token refresh failed"), { name: "NotAuthorizedException" });
751
- }
752
- return await tokenRes.json();
753
- }, (e) => {
754
- console.error("refreshOAuthToken:error", e);
755
- return error_cognito(e);
756
- });
783
+ function refreshOAuthToken(a) {
784
+ return ResultAsync.fromThrowable(async () => {
785
+ const basicAuth = Buffer.from(`${a.clientId}:${a.clientSecret}`).toString("base64");
786
+ const params = new URLSearchParams();
787
+ params.append("grant_type", "refresh_token");
788
+ params.append("refresh_token", a.refreshToken);
789
+ console.log("refreshOAuthToken: params", params.toString());
790
+ const tokenRes = await fetch(`https://${a.cognitoDomain}/oauth2/token`, {
791
+ method: "POST",
792
+ headers: {
793
+ "Content-Type": "application/x-www-form-urlencoded",
794
+ Authorization: `Basic ${basicAuth}`
795
+ },
796
+ body: params.toString()
797
+ });
798
+ if (!tokenRes.ok) {
799
+ console.error("refreshOAuthToken: token exchange failed", await tokenRes.text());
800
+ throw Object.assign(/* @__PURE__ */ new Error("OAuth token refresh failed"), { name: "NotAuthorizedException" });
801
+ }
802
+ return await tokenRes.json();
803
+ }, (e) => {
804
+ console.error("refreshOAuthToken:error", e);
805
+ return error_cognito(e);
806
+ })();
807
+ }
757
808
  //#endregion
758
809
  //#region src/s3/client.ts
759
810
  /**
@@ -943,10 +994,12 @@ function getHttpStatusCode$1(error) {
943
994
  }
944
995
  //#endregion
945
996
  //#region src/s3/signedUrl.ts
946
- const getSignedUrl = ResultAsync.fromThrowable(getSignedUrl$1, (e) => {
947
- console.error("getSignedUrl: Failed to get signed url", e);
948
- error_s3(e);
949
- });
997
+ function getSignedUrl(...args) {
998
+ return ResultAsync.fromThrowable(getSignedUrl$1, (e) => {
999
+ console.error("getSignedUrl: Failed to get signed url", e);
1000
+ return error_s3(e);
1001
+ })(...args);
1002
+ }
950
1003
  //#endregion
951
1004
  //#region src/s3/object.ts
952
1005
  /**
@@ -956,23 +1009,25 @@ const getSignedUrl = ResultAsync.fromThrowable(getSignedUrl$1, (e) => {
956
1009
  * @param {string} key - The key of the object to retrieve.
957
1010
  * @returns {Promise<Buffer>} A promise that resolves to the object data as a Buffer.
958
1011
  */
959
- const getObject = ResultAsync.fromThrowable(async (bucketName, key) => {
960
- const s3 = getS3();
961
- const cmd = new GetObjectCommand({
962
- Bucket: bucketName,
963
- Key: key
964
- });
965
- const stream = (await s3.send(cmd)).Body;
966
- return new Promise((resolve, reject) => {
967
- const chunks = [];
968
- stream.on("data", (chunk) => chunks.push(chunk));
969
- stream.on("end", () => resolve(Buffer.concat(chunks)));
970
- stream.on("error", reject);
971
- });
972
- }, (e) => {
973
- console.error(`getObjectt: Error getting object from S3: ${e}`);
974
- return error_s3(e);
975
- });
1012
+ function getObject(bucketName, key) {
1013
+ return ResultAsync.fromThrowable(async () => {
1014
+ const s3 = getS3();
1015
+ const cmd = new GetObjectCommand({
1016
+ Bucket: bucketName,
1017
+ Key: key
1018
+ });
1019
+ const stream = (await s3.send(cmd)).Body;
1020
+ return new Promise((resolve, reject) => {
1021
+ const chunks = [];
1022
+ stream.on("data", (chunk) => chunks.push(chunk));
1023
+ stream.on("end", () => resolve(Buffer.concat(chunks)));
1024
+ stream.on("error", reject);
1025
+ });
1026
+ }, (e) => {
1027
+ console.error(`getObjectt: Error getting object from S3: ${e}`);
1028
+ return error_s3(e);
1029
+ })();
1030
+ }
976
1031
  /**
977
1032
  * Convenience function to get an object from S3 and return it as a string.
978
1033
  */
@@ -986,22 +1041,24 @@ function getObjectString(bucketName, key) {
986
1041
  * @param {string} key - The key of the object to retrieve.
987
1042
  * @returns {Promise<Buffer>} A promise that resolves to a boolean.
988
1043
  */
989
- const objectExists = ResultAsync.fromThrowable(async (bucketName, key) => {
990
- const s3 = getS3();
991
- try {
992
- const cmd = new HeadObjectCommand({
993
- Bucket: bucketName,
994
- Key: key
995
- });
996
- return (await s3.send(cmd)).$metadata.httpStatusCode === 200;
997
- } catch (e) {
998
- if (is_s3_notFound(e)) return false;
999
- throw e;
1000
- }
1001
- }, (e) => {
1002
- console.error(`objectExists: Error getting object head from S3: ${e}`);
1003
- return error_s3(e);
1004
- });
1044
+ function objectExists(bucketName, key) {
1045
+ return ResultAsync.fromThrowable(async () => {
1046
+ const s3 = getS3();
1047
+ try {
1048
+ const cmd = new HeadObjectCommand({
1049
+ Bucket: bucketName,
1050
+ Key: key
1051
+ });
1052
+ return (await s3.send(cmd)).$metadata.httpStatusCode === 200;
1053
+ } catch (e) {
1054
+ if (is_s3_notFound(e)) return false;
1055
+ throw e;
1056
+ }
1057
+ }, (e) => {
1058
+ console.error(`objectExists: Error getting object head from S3: ${e}`);
1059
+ return error_s3(e);
1060
+ })();
1061
+ }
1005
1062
  //#endregion
1006
1063
  //#region src/dynamo/errors.ts
1007
1064
  const defaultErrors$1 = {
@@ -1602,6 +1659,6 @@ async function readPackageJson(filePath) {
1602
1659
  //#region src/utils/cli.ts
1603
1660
  const colorText = (format, text) => styleText(format, String(text), { validateStream: false });
1604
1661
  //#endregion
1605
- export { HTTPMethods, changePassword, colorText, computeSecretHash, confirmForgotPassword, confirmSignup, createApiRequest, deepDiff, error_cognito, error_dynamo, error_lambda_badRequest, error_lambda_conflict, error_lambda_forbidden, error_lambda_fromCognito, error_lambda_fromDynamo, error_lambda_fromS3, error_lambda_fromSes, error_lambda_internal, error_lambda_notFound, error_lambda_unauthorized, error_s3, error_ses, exists, extractAttributes, extractToc, forgotPassword, getByPath, getCognitoClient, getCookies, getErrorName, getObject, getObjectString, getS3, getSchemaByPath, getSignedUrl, getUserDetails, getUserGroups, isRecord, isSchema, is_s3_notFound, login, logout, objectExists, parseRaw, pruneToShape, readPackageJson, refreshOAuthToken, refreshTokens, resetPassword, response_error, response_ok, response_valibotError, setByPath, signUp, unwrap, verifyOAuthToken, wrapHandler, writeIfDifferent };
1662
+ export { HTTPMethods, changePassword, colorText, computeSecretHash, confirmForgotPassword, confirmSignup, createApiRequest, deepDiff, error_cognito, error_dynamo, error_lambda_badRequest, error_lambda_conflict, error_lambda_forbidden, error_lambda_fromCognito, error_lambda_fromDynamo, error_lambda_fromS3, error_lambda_fromSes, error_lambda_internal, error_lambda_notFound, error_lambda_unauthorized, error_s3, error_ses, exists, extractAttributes, extractToc, forgotPassword, getByPath, getCognitoClient, getCookies, getErrorName, getObject, getObjectString, getS3, getSchemaByPath, getSignedUrl, getUserDetails, getUserGroups, isRecord, isSchema, is_s3_notFound, login, logout, objectExists, parseRaw, pruneToShape, readPackageJson, refreshOAuthToken, refreshTokens, refreshTokensAuth, resetPassword, response_error, response_ok, response_valibotError, setByPath, signUp, unwrap, verifyOAuthToken, wrapHandler, writeIfDifferent };
1606
1663
 
1607
1664
  //# sourceMappingURL=index.mjs.map