@zuplo/runtime 5.1586.0 → 5.1588.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.
package/index.d.ts CHANGED
@@ -109,11 +109,11 @@ declare interface AmberfloMeteringProperties extends Omit<AmberfloMeteringIngest
109
109
  export declare const ApiAuthKeyInboundPolicy: typeof ApiKeyInboundPolicy;
110
110
 
111
111
  /**
112
- * The options for this policy
112
+ * The options for this policy.
113
113
  */
114
114
  export declare interface ApiAuthKeyInboundPolicyOptions {
115
115
  /**
116
- * If 'true' allows the request to continue even if authenticated. When 'false' (the default) any unauthenticated request is automatically rejected with a 401
116
+ * If 'true' allows the request to continue even if authenticated. When 'false' (the default) any unauthenticated request is automatically rejected with a 401.
117
117
  */
118
118
  allowUnauthenticatedRequests?: boolean;
119
119
  }
@@ -144,7 +144,7 @@ export declare interface ApiAuthKeyInboundPolicyOptions {
144
144
  export declare function ApiKeyInboundPolicy(request: ZuploRequest, context: ZuploContext, unparsedOptions: ApiKeyInboundPolicyOptions, policyName: string): Promise<ZuploRequest<any, Record<string, string>, Record<string, string>> | Response>;
145
145
 
146
146
  /**
147
- * The options for this policy
147
+ * The options for this policy.
148
148
  */
149
149
  export declare interface ApiKeyInboundPolicyOptions {
150
150
  /**
@@ -259,7 +259,7 @@ declare interface AuditLogRequestFilter {
259
259
  export declare const Auth0JwtInboundPolicy: InboundPolicyHandler<Auth0JwtInboundPolicyOptions>;
260
260
 
261
261
  /**
262
- * The options for this policy
262
+ * The options for this policy.
263
263
  */
264
264
  export declare interface Auth0JwtInboundPolicyOptions {
265
265
  /**
@@ -267,11 +267,11 @@ export declare interface Auth0JwtInboundPolicyOptions {
267
267
  */
268
268
  allowUnauthenticatedRequests?: boolean;
269
269
  /**
270
- * Your Auth0 domain. For example, my-company.auth0.com
270
+ * Your Auth0 domain. For example, `my-company.auth0.com`.
271
271
  */
272
272
  auth0Domain: string;
273
273
  /**
274
- * The Auth0 audience of your API, for example https://api.example.com/
274
+ * The Auth0 audience of your API, for example `https://api.example.com/`.
275
275
  */
276
276
  audience?: string;
277
277
  }
@@ -429,7 +429,7 @@ declare abstract class BaseKeyValueStore {
429
429
  }
430
430
 
431
431
  /**
432
- * An account object
432
+ * An account object.
433
433
  */
434
434
  declare interface BasicAuthAccount {
435
435
  /**
@@ -437,11 +437,11 @@ declare interface BasicAuthAccount {
437
437
  */
438
438
  username: string;
439
439
  /**
440
- * The password for the account - note we recommend storing this in environment variables
440
+ * The password for the account - note we recommend storing this in environment variables.
441
441
  */
442
442
  password: string;
443
443
  /**
444
- * The data payload you want associated with this account (this will be the `data` property on `request.user`)
444
+ * The data payload you want associated with this account (this will be the `data` property on `request.user`).
445
445
  */
446
446
  data?: {
447
447
  [k: string]: unknown;
@@ -473,15 +473,15 @@ declare interface BasicAuthAccount {
473
473
  export declare const BasicAuthInboundPolicy: InboundPolicyHandler<BasicAuthInboundPolicyOptions>;
474
474
 
475
475
  /**
476
- * The options for this policy
476
+ * The options for this policy.
477
477
  */
478
478
  export declare interface BasicAuthInboundPolicyOptions {
479
479
  /**
480
- * An array of account objects (username, password and data properties)
480
+ * An array of account objects (username, password and data properties).
481
481
  */
482
482
  accounts: BasicAuthAccount[];
483
483
  /**
484
- * If 'true' allows the request to continue even if authenticated. When 'false' (the default) any unauthenticated request is automatically rejected with a 401
484
+ * If 'true' allows the request to continue even if authenticated. When 'false' (the default) any unauthenticated request is automatically rejected with a 401.
485
485
  */
486
486
  allowUnauthenticatedRequests?: boolean;
487
487
  }
@@ -542,7 +542,7 @@ declare interface CacheOptions {
542
542
  export declare function CachingInboundPolicy(request: ZuploRequest, context: ZuploContext, options: CachingInboundPolicyOptions, policyName: string): Promise<ZuploRequest<any, Record<string, string>, Record<string, string>> | Response>;
543
543
 
544
544
  /**
545
- * The options for this policy
545
+ * The options for this policy.
546
546
  */
547
547
  export declare interface CachingInboundPolicyOptions {
548
548
  /**
@@ -550,11 +550,11 @@ export declare interface CachingInboundPolicyOptions {
550
550
  */
551
551
  cacheId?: string;
552
552
  /**
553
- * By default, the Authorization header is always considered in the caching policy. You can disable by setting this to true
553
+ * By default, the Authorization header is always considered in the caching policy. You can disable by setting this to `true`.
554
554
  */
555
555
  dangerouslyIgnoreAuthorizationHeader?: boolean;
556
556
  /**
557
- * The headers to be considered when caching
557
+ * The headers to be considered when caching.
558
558
  */
559
559
  headers?: string[];
560
560
  /**
@@ -562,7 +562,7 @@ export declare interface CachingInboundPolicyOptions {
562
562
  */
563
563
  cacheHttpMethods?: ("GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD")[];
564
564
  /**
565
- * The timeout of the cache in seconds
565
+ * The timeout of the cache in seconds.
566
566
  */
567
567
  expirationSecondsTtl?: number;
568
568
  /**
@@ -585,11 +585,11 @@ export declare interface CachingInboundPolicyOptions {
585
585
  export declare const ChangeMethodInboundPolicy: InboundPolicyHandler<ChangeMethodInboundPolicyOptions>;
586
586
 
587
587
  /**
588
- * The options for this policy
588
+ * The options for this policy.
589
589
  */
590
590
  export declare interface ChangeMethodInboundPolicyOptions {
591
591
  /**
592
- * The HTTP Method to be used, e.g. POST, GET, PUT, PATCH, etc
592
+ * The HTTP Method to be used, e.g. POST, GET, PUT, PATCH, etc.
593
593
  */
594
594
  method: string;
595
595
  }
@@ -608,11 +608,11 @@ export declare interface ChangeMethodInboundPolicyOptions {
608
608
  export declare const ClearHeadersInboundPolicy: InboundPolicyHandler<ClearHeadersInboundPolicyOptions>;
609
609
 
610
610
  /**
611
- * The options for this policy
611
+ * The options for this policy.
612
612
  */
613
613
  export declare interface ClearHeadersInboundPolicyOptions {
614
614
  /**
615
- * The headers that should not be removed
615
+ * The headers that should not be removed.
616
616
  */
617
617
  exclude?: string[];
618
618
  }
@@ -631,11 +631,11 @@ export declare interface ClearHeadersInboundPolicyOptions {
631
631
  export declare const ClearHeadersOutboundPolicy: OutboundPolicyHandler<ClearHeadersOutboundPolicyOptions>;
632
632
 
633
633
  /**
634
- * The options for this policy
634
+ * The options for this policy.
635
635
  */
636
636
  export declare interface ClearHeadersOutboundPolicyOptions {
637
637
  /**
638
- * The headers that should not be removed
638
+ * The headers that should not be removed.
639
639
  */
640
640
  exclude?: string[];
641
641
  }
@@ -659,7 +659,7 @@ export declare interface ClearHeadersOutboundPolicyOptions {
659
659
  export declare const ClerkJwtInboundPolicy: InboundPolicyHandler<ClerkJwtInboundPolicyOptions>;
660
660
 
661
661
  /**
662
- * The options for this policy
662
+ * The options for this policy.
663
663
  */
664
664
  export declare interface ClerkJwtInboundPolicyOptions {
665
665
  /**
@@ -667,7 +667,7 @@ export declare interface ClerkJwtInboundPolicyOptions {
667
667
  */
668
668
  allowUnauthenticatedRequests?: boolean;
669
669
  /**
670
- * Your Clerk frontend api url, i.e. 'https://sensible-skunk-49.clerk.accounts.dev'. Can be found in the Clerk portal: https://dashboard.clerk.com/last-active?path=api-keys
670
+ * Your Clerk frontend api url, i.e. `https://sensible-skunk-49.clerk.accounts.dev`. Can be found in the Clerk portal: https://dashboard.clerk.com/last-active?path=api-keys.
671
671
  */
672
672
  frontendApiUrl: string;
673
673
  }
@@ -694,7 +694,7 @@ export declare interface ClerkJwtInboundPolicyOptions {
694
694
  export declare const CognitoJwtInboundPolicy: InboundPolicyHandler<CognitoJwtInboundPolicyOptions>;
695
695
 
696
696
  /**
697
- * The options for this policy
697
+ * The options for this policy.
698
698
  */
699
699
  export declare interface CognitoJwtInboundPolicyOptions {
700
700
  /**
@@ -702,11 +702,11 @@ export declare interface CognitoJwtInboundPolicyOptions {
702
702
  */
703
703
  allowUnauthenticatedRequests?: boolean;
704
704
  /**
705
- * The AWS region where your Cognito instance is deployed
705
+ * The AWS region where your Cognito instance is deployed.
706
706
  */
707
707
  region: string;
708
708
  /**
709
- * The user pool identifier
709
+ * The user pool identifier.
710
710
  */
711
711
  userPoolId: string;
712
712
  }
@@ -737,11 +737,11 @@ export declare type CompatibilityDate = "2023-03-14";
737
737
  export declare const CompositeInboundPolicy: InboundPolicyHandler<CompositeInboundPolicyOptions>;
738
738
 
739
739
  /**
740
- * The options for this policy
740
+ * The options for this policy.
741
741
  */
742
742
  export declare interface CompositeInboundPolicyOptions {
743
743
  /**
744
- * The list of policy references (beware circular references)
744
+ * The list of policy references (beware circular references).
745
745
  */
746
746
  policies?: string[];
747
747
  }
@@ -929,7 +929,7 @@ export declare interface ErrorHandler {
929
929
  export declare const FirebaseJwtInboundPolicy: InboundPolicyHandler<FirebaseJwtInboundPolicyOptions>;
930
930
 
931
931
  /**
932
- * The options for this policy
932
+ * The options for this policy.
933
933
  */
934
934
  export declare interface FirebaseJwtInboundPolicyOptions {
935
935
  /**
@@ -937,7 +937,7 @@ export declare interface FirebaseJwtInboundPolicyOptions {
937
937
  */
938
938
  allowUnauthenticatedRequests?: boolean;
939
939
  /**
940
- * Your Firebase Project ID
940
+ * Your Firebase Project ID.
941
941
  */
942
942
  projectId: string;
943
943
  }
@@ -956,11 +956,11 @@ export declare interface FirebaseJwtInboundPolicyOptions {
956
956
  export declare const FormDataToJsonInboundPolicy: InboundPolicyHandler<FormDataToJsonInboundPolicyOptions>;
957
957
 
958
958
  /**
959
- * The options for this policy
959
+ * The options for this policy.
960
960
  */
961
961
  export declare interface FormDataToJsonInboundPolicyOptions {
962
962
  /**
963
- * Should the policy return an error if the request is not of the type form data
963
+ * Should the policy return an error if the request is not of the type form data.
964
964
  */
965
965
  badRequestIfNotFormData?: boolean;
966
966
  /**
@@ -985,7 +985,7 @@ export declare interface FormDataToJsonInboundPolicyOptions {
985
985
  export declare const GeoFilterInboundPolicy: InboundPolicyHandler<GeoFilterInboundPolicyOptions>;
986
986
 
987
987
  /**
988
- * The options for this policy
988
+ * The options for this policy.
989
989
  */
990
990
  export declare interface GeoFilterInboundPolicyOptions {
991
991
  block?: GeoSpec;
@@ -998,15 +998,15 @@ export declare interface GeoFilterInboundPolicyOptions {
998
998
 
999
999
  declare interface GeoSpec {
1000
1000
  /**
1001
- * comma separated string of country codes to allow (e.g. "US, CA")
1001
+ * comma separated string of country codes to allow (e.g. "US, CA").
1002
1002
  */
1003
1003
  countries?: string;
1004
1004
  /**
1005
- * comma separated string of region codes to allow (e.g. "TX, WA")
1005
+ * comma separated string of region codes to allow (e.g. "TX, WA").
1006
1006
  */
1007
1007
  regionCodes?: string;
1008
1008
  /**
1009
- * comma separated string of ASNs to allow (e.g. "395747, 28304")
1009
+ * comma separated string of ASNs to allow (e.g. "395747, 28304").
1010
1010
  */
1011
1011
  asns?: string;
1012
1012
  }
@@ -2205,11 +2205,11 @@ export declare function isZuploReadableEnvVariableName(name: string): boolean;
2205
2205
  export declare const JWTScopeValidationInboundPolicy: InboundPolicyHandler<JWTScopeValidationInboundPolicyOptions>;
2206
2206
 
2207
2207
  /**
2208
- * The options for this policy
2208
+ * The options for this policy.
2209
2209
  */
2210
2210
  export declare interface JWTScopeValidationInboundPolicyOptions {
2211
2211
  /**
2212
- * An array of of JWT scopes
2212
+ * An array of of JWT scopes.
2213
2213
  */
2214
2214
  scopes: string[];
2215
2215
  }
@@ -2346,7 +2346,7 @@ declare interface MetricsType {
2346
2346
  }
2347
2347
 
2348
2348
  /**
2349
- * The options for this policy
2349
+ * The options for this policy.
2350
2350
  */
2351
2351
  export declare interface MockApiInboundOptions {
2352
2352
  /**
@@ -2455,7 +2455,7 @@ declare interface NotFoundOptions {
2455
2455
  export declare const OktaJwtInboundPolicy: InboundPolicyHandler<OktaJwtInboundPolicyOptions>;
2456
2456
 
2457
2457
  /**
2458
- * The options for this policy
2458
+ * The options for this policy.
2459
2459
  */
2460
2460
  export declare interface OktaJwtInboundPolicyOptions {
2461
2461
  /**
@@ -2463,11 +2463,11 @@ export declare interface OktaJwtInboundPolicyOptions {
2463
2463
  */
2464
2464
  allowUnauthenticatedRequests?: boolean;
2465
2465
  /**
2466
- * Your Okta authorization server's issuer URL. For example, https://dev-12345.okta.com/oauth2/abc
2466
+ * Your Okta authorization server's issuer URL. For example, `https://dev-12345.okta.com/oauth2/abc`.
2467
2467
  */
2468
2468
  issuerUrl: string;
2469
2469
  /**
2470
- * The Okta audience of your API, for example api://my-api
2470
+ * The Okta audience of your API, for example `api://my-api`.
2471
2471
  */
2472
2472
  audience?: string;
2473
2473
  }
@@ -2538,7 +2538,7 @@ declare interface OpenIdJwtInboundPolicyInternalOptions extends Omit<OpenIdJwtIn
2538
2538
  }
2539
2539
 
2540
2540
  /**
2541
- * The options for this policy
2541
+ * The options for this policy.
2542
2542
  */
2543
2543
  export declare interface OpenIdJwtInboundPolicyOptions {
2544
2544
  /**
@@ -2554,7 +2554,7 @@ export declare interface OpenIdJwtInboundPolicyOptions {
2554
2554
  */
2555
2555
  jwkUrl?: string;
2556
2556
  /**
2557
- * The key used to verify the signature of the JWT token (either this or `jwkUrl` must be set)
2557
+ * The key used to verify the signature of the JWT token (either this or `jwkUrl` must be set).
2558
2558
  */
2559
2559
  secret?: string;
2560
2560
  /**
@@ -2747,7 +2747,7 @@ export declare class ProblemResponseFormatter {
2747
2747
  export declare const PropelAuthJwtInboundPolicy: InboundPolicyHandler<PropelAuthJwtInboundPolicyOptions>;
2748
2748
 
2749
2749
  /**
2750
- * The options for this policy
2750
+ * The options for this policy.
2751
2751
  */
2752
2752
  export declare interface PropelAuthJwtInboundPolicyOptions {
2753
2753
  /**
@@ -2755,7 +2755,7 @@ export declare interface PropelAuthJwtInboundPolicyOptions {
2755
2755
  */
2756
2756
  allowUnauthenticatedRequests?: boolean;
2757
2757
  /**
2758
- * Your PropelAuth authUrl. For example, https://6587563.propelauthtest.com
2758
+ * Your PropelAuth authUrl. For example, `https://6587563.propelauthtest.com`.
2759
2759
  */
2760
2760
  authUrl: string;
2761
2761
  /**
@@ -2767,12 +2767,12 @@ export declare interface PropelAuthJwtInboundPolicyOptions {
2767
2767
  /* Excluded from this release type: purgeGatewayCache */
2768
2768
 
2769
2769
  /**
2770
- * The identifying element of the request that enforces distinct rate limits. For example, you can limit by `user`, `ip`, `function` or `all` - function allows you to specify a simple function to create a string identifier to create a rate-limit group
2770
+ * The identifying element of the request that enforces distinct rate limits. For example, you can limit by `user`, `ip`, `function` or `all` - function allows you to specify a simple function to create a string identifier to create a rate-limit group.
2771
2771
  */
2772
2772
  declare type RateLimitByType = "user" | "ip" | "function" | "all";
2773
2773
 
2774
2774
  /**
2775
- * Adds the retry-after header, defaults to true
2775
+ * Adds the retry-after header.
2776
2776
  */
2777
2777
  declare type RateLimitHeaderMode = "none" | "retry-after";
2778
2778
 
@@ -2806,20 +2806,20 @@ export { RateLimitInboundPolicy as BasicRateLimitInboundPolicy }
2806
2806
  export { RateLimitInboundPolicy }
2807
2807
 
2808
2808
  /**
2809
- * The options for this policy
2809
+ * The options for this policy.
2810
2810
  */
2811
2811
  declare interface RateLimitInboundPolicyOptions {
2812
2812
  rateLimitBy: RateLimitByType;
2813
2813
  /**
2814
- * The max number of requests allowed in the given time window
2814
+ * The max number of requests allowed in the given time window.
2815
2815
  */
2816
2816
  requestsAllowed: number;
2817
2817
  /**
2818
- * The time window in which the requests are rate-limited. The count restarts after each window expires
2818
+ * The time window in which the requests are rate-limited. The count restarts after each window expires.
2819
2819
  */
2820
2820
  timeWindowMinutes: number;
2821
2821
  /**
2822
- * The function that returns dynamic configuration data. Used only with `rateLimitBy=function`
2822
+ * The function that returns dynamic configuration data. Used only with `rateLimitBy=function`.
2823
2823
  */
2824
2824
  identifier?: {
2825
2825
  /**
@@ -2827,13 +2827,13 @@ declare interface RateLimitInboundPolicyOptions {
2827
2827
  */
2828
2828
  export: string;
2829
2829
  /**
2830
- * Specifies the module to load your custom bucket function, in the format `$import(./modules/my-module)`
2830
+ * Specifies the module to load your custom bucket function, in the format `$import(./modules/my-module)`.
2831
2831
  */
2832
2832
  module: string;
2833
2833
  };
2834
2834
  headerMode?: RateLimitHeaderMode;
2835
2835
  /**
2836
- * If true, the policy will throw an error in the event there is a problem connecting to the rate limit service
2836
+ * If true, the policy will throw an error in the event there is a problem connecting to the rate limit service.
2837
2837
  */
2838
2838
  throwOnFailure?: boolean;
2839
2839
  mode?: RateLimitMode;
@@ -2851,7 +2851,7 @@ declare type RateLimitMode = "strict" | "async";
2851
2851
  */
2852
2852
  declare interface ReadmeMeteringInboundPolicyOptions {
2853
2853
  /**
2854
- * The API key to use when sending metrics calls to Readme
2854
+ * The API key to use when sending metrics calls to Readme.
2855
2855
  */
2856
2856
  apiKey: string;
2857
2857
  /**
@@ -2916,7 +2916,7 @@ export declare function redirectHandler(request: ZuploRequest, context: ZuploCon
2916
2916
  export declare const RemoveHeadersInboundPolicy: InboundPolicyHandler<RemoveHeadersInboundPolicyOptions>;
2917
2917
 
2918
2918
  /**
2919
- * The options for this policy
2919
+ * The options for this policy.
2920
2920
  */
2921
2921
  export declare interface RemoveHeadersInboundPolicyOptions {
2922
2922
  /**
@@ -2939,7 +2939,7 @@ export declare interface RemoveHeadersInboundPolicyOptions {
2939
2939
  export declare const RemoveHeadersOutboundPolicy: OutboundPolicyHandler<RemoveHeadersOutboundPolicyOptions>;
2940
2940
 
2941
2941
  /**
2942
- * The options for this policy
2942
+ * The options for this policy.
2943
2943
  */
2944
2944
  export declare interface RemoveHeadersOutboundPolicyOptions {
2945
2945
  /**
@@ -2962,7 +2962,7 @@ export declare interface RemoveHeadersOutboundPolicyOptions {
2962
2962
  export declare const RemoveQueryParamsInboundPolicy: InboundPolicyHandler<RemoveQueryParamsInboundPolicyOptions>;
2963
2963
 
2964
2964
  /**
2965
- * The options for this policy
2965
+ * The options for this policy.
2966
2966
  */
2967
2967
  export declare interface RemoveQueryParamsInboundPolicyOptions {
2968
2968
  /**
@@ -2985,19 +2985,19 @@ export declare interface RemoveQueryParamsInboundPolicyOptions {
2985
2985
  export declare const ReplaceStringOutboundPolicy: OutboundPolicyHandler<ReplaceStringOutboundPolicyOptions>;
2986
2986
 
2987
2987
  /**
2988
- * The options for this policy
2988
+ * The options for this policy.
2989
2989
  */
2990
2990
  export declare interface ReplaceStringOutboundPolicyOptions {
2991
2991
  /**
2992
- * The type of string replacement to perform
2992
+ * The type of string replacement to perform.
2993
2993
  */
2994
2994
  mode: "regexp" | "string";
2995
2995
  /**
2996
- * The pattern to match
2996
+ * The pattern to match.
2997
2997
  */
2998
2998
  match: string;
2999
2999
  /**
3000
- * The value to each match is replaced with
3000
+ * The value to each match is replaced with.
3001
3001
  */
3002
3002
  replaceWith: string;
3003
3003
  }
@@ -3016,11 +3016,11 @@ export declare interface ReplaceStringOutboundPolicyOptions {
3016
3016
  export declare const RequestSizeLimitInboundPolicy: InboundPolicyHandler<RequestSizeLimitInboundPolicyOptions>;
3017
3017
 
3018
3018
  /**
3019
- * The options for this policy
3019
+ * The options for this policy.
3020
3020
  */
3021
3021
  export declare interface RequestSizeLimitInboundPolicyOptions {
3022
3022
  /**
3023
- * The maximum size of the request in bytes
3023
+ * The maximum size of the request in bytes.
3024
3024
  */
3025
3025
  maxSizeInBytes: number;
3026
3026
  /**
@@ -3059,7 +3059,7 @@ export declare interface RequestUser<TUserData = any> {
3059
3059
  export declare const RequestValidationInboundPolicy: InboundPolicyHandler<RequestValidationInboundPolicyOptions>;
3060
3060
 
3061
3061
  /**
3062
- * The options for this policy
3062
+ * The options for this policy.
3063
3063
  */
3064
3064
  export declare interface RequestValidationInboundPolicyOptions {
3065
3065
  /**
@@ -3104,15 +3104,15 @@ export declare interface RequestValidationInboundPolicyOptions {
3104
3104
  export declare const RequireOriginInboundPolicy: InboundPolicyHandler<RequireOriginInboundPolicyOptions>;
3105
3105
 
3106
3106
  /**
3107
- * The options for this policy
3107
+ * The options for this policy.
3108
3108
  */
3109
3109
  export declare interface RequireOriginInboundPolicyOptions {
3110
3110
  /**
3111
- * A comma separated string containing valid origins
3111
+ * A comma separated string containing valid origins.
3112
3112
  */
3113
3113
  origins: string;
3114
3114
  /**
3115
- * The `detail` of the HTTP Problem response, if the origin is missing or disallowed
3115
+ * The `detail` of the HTTP Problem response, if the origin is missing or disallowed.
3116
3116
  */
3117
3117
  failureDetail?: string;
3118
3118
  }
@@ -3287,11 +3287,11 @@ export declare interface ServiceProvider {
3287
3287
  export declare const SetBodyInboundPolicy: InboundPolicyHandler<SetBodyInboundPolicyOptions>;
3288
3288
 
3289
3289
  /**
3290
- * The options for this policy
3290
+ * The options for this policy.
3291
3291
  */
3292
3292
  export declare interface SetBodyInboundPolicyOptions {
3293
3293
  /**
3294
- * The value to set for the body
3294
+ * The value to set for the body.
3295
3295
  */
3296
3296
  body: string;
3297
3297
  }
@@ -3314,7 +3314,7 @@ export declare interface SetBodyInboundPolicyOptions {
3314
3314
  export declare const SetHeadersInboundPolicy: InboundPolicyHandler<SetHeadersInboundPolicyOptions>;
3315
3315
 
3316
3316
  /**
3317
- * The options for this policy
3317
+ * The options for this policy.
3318
3318
  */
3319
3319
  export declare interface SetHeadersInboundPolicyOptions {
3320
3320
  /**
@@ -3322,24 +3322,24 @@ export declare interface SetHeadersInboundPolicyOptions {
3322
3322
  */
3323
3323
  headers: {
3324
3324
  /**
3325
- * The name of the header
3325
+ * The name of the header.
3326
3326
  */
3327
3327
  name: string;
3328
3328
  /**
3329
- * The value of the header
3329
+ * The value of the header.
3330
3330
  */
3331
3331
  value: string;
3332
3332
  /**
3333
- * Overwrite the value if the header is already present in the request
3333
+ * Overwrite the value if the header is already present in the request.
3334
3334
  */
3335
3335
  overwrite?: boolean;
3336
3336
  }[];
3337
3337
  }
3338
3338
 
3339
3339
  /**
3340
- * Adds or sets headers on the on the outgoing.
3340
+ * Adds or sets headers on the on the outgoing response.
3341
3341
  *
3342
- * @title Set Status Code
3342
+ * @title Set Headers
3343
3343
  * @public
3344
3344
  * @param request - The ZuploRequest
3345
3345
  * @param context - The ZuploContext
@@ -3350,7 +3350,7 @@ export declare interface SetHeadersInboundPolicyOptions {
3350
3350
  export declare const SetHeadersOutboundPolicy: OutboundPolicyHandler<SetHeadersOutboundPolicyOptions>;
3351
3351
 
3352
3352
  /**
3353
- * The options for this policy
3353
+ * The options for this policy.
3354
3354
  */
3355
3355
  export declare interface SetHeadersOutboundPolicyOptions {
3356
3356
  /**
@@ -3388,7 +3388,7 @@ export declare function setMoesifContext(context: ZuploContext, moesifContext: M
3388
3388
  export declare const SetQueryParamsInboundPolicy: InboundPolicyHandler<SetQueryParamsInboundPolicyOptions>;
3389
3389
 
3390
3390
  /**
3391
- * The options for this policy
3391
+ * The options for this policy.
3392
3392
  */
3393
3393
  export declare interface SetQueryParamsInboundPolicyOptions {
3394
3394
  /**
@@ -3396,11 +3396,11 @@ export declare interface SetQueryParamsInboundPolicyOptions {
3396
3396
  */
3397
3397
  params: {
3398
3398
  /**
3399
- * The name of the param
3399
+ * The name of the param.
3400
3400
  */
3401
3401
  name: string;
3402
3402
  /**
3403
- * The value of the param
3403
+ * The value of the param.
3404
3404
  */
3405
3405
  value: string;
3406
3406
  /**
@@ -3424,11 +3424,11 @@ export declare interface SetQueryParamsInboundPolicyOptions {
3424
3424
  export declare const SetStatusOutboundPolicy: OutboundPolicyHandler<SetStatusOutboundPolicyOptions>;
3425
3425
 
3426
3426
  /**
3427
- * The options for this policy
3427
+ * The options for this policy.
3428
3428
  */
3429
3429
  export declare interface SetStatusOutboundPolicyOptions {
3430
3430
  /**
3431
- * The status code to be used in the response
3431
+ * The status code to be used in the response.
3432
3432
  */
3433
3433
  status?: number;
3434
3434
  /**
@@ -3451,11 +3451,11 @@ export declare interface SetStatusOutboundPolicyOptions {
3451
3451
  export declare const SleepInboundPolicy: InboundPolicyHandler<SleepInboundPolicyOptions>;
3452
3452
 
3453
3453
  /**
3454
- * The options for this policy
3454
+ * The options for this policy.
3455
3455
  */
3456
3456
  export declare interface SleepInboundPolicyOptions {
3457
3457
  /**
3458
- * The number of milliseconds to delay the request
3458
+ * The number of milliseconds to delay the request.
3459
3459
  */
3460
3460
  sleepInMs: number;
3461
3461
  }
@@ -3502,11 +3502,11 @@ export declare class SumoLogicLoggingPlugin extends LogPlugin {
3502
3502
  export declare const SupabaseJwtInboundPolicy: InboundPolicyHandler<SupabaseJwtInboundPolicyOptions>;
3503
3503
 
3504
3504
  /**
3505
- * The options for this policy
3505
+ * The options for this policy.
3506
3506
  */
3507
3507
  export declare interface SupabaseJwtInboundPolicyOptions {
3508
3508
  /**
3509
- * The key used to verify the signature of the JWT token
3509
+ * The key used to verify the signature of the JWT token.
3510
3510
  */
3511
3511
  secret: string;
3512
3512
  /**
@@ -3552,7 +3552,7 @@ export declare interface SupabaseJwtInboundPolicyOptions {
3552
3552
  export declare const UpstreamAzureAdServiceAuthInboundPolicy: InboundPolicyHandler<UpstreamAzureAdServiceAuthInboundPolicyOptions>;
3553
3553
 
3554
3554
  /**
3555
- * The options for this policy
3555
+ * The options for this policy.
3556
3556
  */
3557
3557
  export declare interface UpstreamAzureAdServiceAuthInboundPolicyOptions {
3558
3558
  /**
@@ -3603,7 +3603,7 @@ export declare interface UpstreamAzureAdServiceAuthInboundPolicyOptions {
3603
3603
  export declare const UpstreamFirebaseAdminAuthInboundPolicy: InboundPolicyHandler<UpstreamFirebaseAdminAuthInboundPolicyOptions>;
3604
3604
 
3605
3605
  /**
3606
- * The options for this policy
3606
+ * The options for this policy.
3607
3607
  */
3608
3608
  export declare interface UpstreamFirebaseAdminAuthInboundPolicyOptions {
3609
3609
  /**
@@ -3646,7 +3646,7 @@ export declare interface UpstreamFirebaseAdminAuthInboundPolicyOptions {
3646
3646
  export declare const UpstreamFirebaseUserAuthInboundPolicy: InboundPolicyHandler<UpstreamFirebaseUserAuthInboundPolicyOptions>;
3647
3647
 
3648
3648
  /**
3649
- * The options for this policy
3649
+ * The options for this policy.
3650
3650
  */
3651
3651
  export declare interface UpstreamFirebaseUserAuthInboundPolicyOptions {
3652
3652
  /**
@@ -3658,7 +3658,7 @@ export declare interface UpstreamFirebaseUserAuthInboundPolicyOptions {
3658
3658
  */
3659
3659
  userId?: string;
3660
3660
  /**
3661
- * The property on the incoming request.user object to retrieve the value of the userId
3661
+ * The property on the incoming request.user object to retrieve the value of the userId.
3662
3662
  */
3663
3663
  userIdPropertyPath?: string;
3664
3664
  /**
@@ -3704,7 +3704,7 @@ export declare interface UpstreamFirebaseUserAuthInboundPolicyOptions {
3704
3704
  export declare const UpstreamGcpJwtInboundPolicy: InboundPolicyHandler<UpstreamGcpJwtInboundPolicyOptions>;
3705
3705
 
3706
3706
  /**
3707
- * The options for this policy
3707
+ * The options for this policy.
3708
3708
  */
3709
3709
  export declare interface UpstreamGcpJwtInboundPolicyOptions {
3710
3710
  /**
@@ -3748,16 +3748,16 @@ export declare interface UpstreamGcpJwtInboundPolicyOptions {
3748
3748
  export declare const UpstreamGcpServiceAuthInboundPolicy: InboundPolicyHandler<UpstreamGcpServiceAuthInboundPolicyOptions>;
3749
3749
 
3750
3750
  /**
3751
- * The options for this policy
3751
+ * The options for this policy.
3752
3752
  */
3753
3753
  export declare interface UpstreamGcpServiceAuthInboundPolicyOptions {
3754
3754
  /**
3755
- * The audience for the service to be called. This is typically the URL of your service endpoint like 'https://my-service-a2ev-uc.a.run.app'
3755
+ * The audience for the service to be called. This is typically the URL of your service endpoint like 'https://my-service-a2ev-uc.a.run.app'.
3756
3756
  */
3757
3757
  audience: string;
3758
3758
  /**
3759
3759
  * The Google Service Account key in JSON format. Note you can load this from environment variables using the `$env(ENV_VAR)` syntax.
3760
- * @see {@link https://developers.google.com/workspace/guides/create-credentials|Create access credentials}
3760
+ * @see {@link https://developers.google.com/workspace/guides/create-credentials|Create access credentials}.
3761
3761
  */
3762
3762
  serviceAccountJson: string;
3763
3763
  /**
@@ -3827,7 +3827,7 @@ declare interface ValidateJsonSchemaInboundInternalOptions extends Omit<Validate
3827
3827
  }
3828
3828
 
3829
3829
  /**
3830
- * The options for this policy
3830
+ * The options for this policy.
3831
3831
  */
3832
3832
  export declare interface ValidateJsonSchemaInboundOptions {
3833
3833
  /**
package/index.minified.js CHANGED
@@ -59,5 +59,5 @@
59
59
  `,this.signedHeaders,await this.hexBodyHash()].join(`
60
60
  `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new E("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=lr(await fi(this.body||""))}return e}};async function ot(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?dr.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,dr.encode(e))}s(ot,"hmac");async function fi(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?dr.encode(t):t)}s(fi,"hash");function lr(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}s(lr,"buf2hex");function hi(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(hi,"encodeRfc3986");function Ku(t,e){let{hostname:n,pathname:r}=t,o=n.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",i="s3";else if(i==="iot")n.startsWith("iot.")?i="execute-api":n.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?i="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in mi?[mi[i],a]:[i,a]}s(Ku,"guessServiceRegion");function Wu(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}s(Wu,"b64ToUint6");function bi(t,e){let n=t.replace(/[^A-Za-z0-9+/]/g,""),r=n.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,i=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=Wu(n.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)i[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return i}s(bi,"base64Decode");function Vt(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s(Vt,"uint6ToB64");function Ri(t){let e=2,n="",r=t.length,o=0;for(let i=0;i<r;i++)e=i%3,o|=t[i]<<(16>>>e&24),(e===2||t.length-i===1)&&(n+=String.fromCodePoint(Vt(o>>>18&63),Vt(o>>>12&63),Vt(o>>>6&63),Vt(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}s(Ri,"base64Encode");function _e(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s(_e,"numberToString");function Yu(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=_e(Math.floor(n/60)),i=_e(n%60);return`${r}${o}${i}`}s(Yu,"getCLFOffset");function gr(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=_e(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),i=_e(t.getHours()),a=_e(t.getMinutes()),u=_e(t.getSeconds()),c=Yu(t);return`${n}/${r}/${o}:${i}:${a}:${u} ${c}`}s(gr,"toCLFDate");var wi=(0,Pi.debug)("zuplo:runtime"),Qu="X-Amzn-Trace-Id",Xu="x-amzn-errortype",Ei=[],ec=s(async(t,e,n)=>{let r=n;for await(let o of Ei)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),j=class extends E{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(Qu)??void 0,this.errorType=n.get(Xu)??void 0}},Ii={addSendingAwsLambdaEventHook:t=>{Ei.push(t)}};async function xi(t,e){let{accessKeyId:n,secretAccessKey:r,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!n)throw new f("awsAccessKeyId is not set in the handler options");if(!r)throw new f("secretAccessKey is not set in the handler options");if(!o)throw new f("region is not set in the handler options");if(!i)throw new f("functionName is not set in the handler options");let l=new Se({accessKeyId:n,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(wi(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,R]=await oc(t,{binaryMediaTypes:c}),{options:m}=e.route.handler,y;m&&typeof m=="object"&&"payloadFormatVersion"in m&&m.payloadFormatVersion==="2.0"?y=rc(t,e):y=await nc(t,e,{useAwsResourcePathStyle:u}),wi("Calling onSendingAwsLambdaEvent hook");let P=await ec(t,e,y);P.body=p,P.isBase64Encoded=R;let w=await l.fetch(d,{body:JSON.stringify(P)});try{return tc(w)}catch(v){if(v instanceof j){let C=m&&typeof m=="object"&&"returnAmazonTraceIdHeader"in m&&m.returnAmazonTraceIdHeader&&v.traceId?{AMZN_TRACE_ID_HEADER:v.traceId}:void 0;return I.internalServerError(t,e,void 0,C)}throw v}}s(xi,"awsLambdaHandler");async function tc(t){let e;try{e=await t.json()}catch{throw new j("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new j(e.message,t.headers):new j(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new j(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let n=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new j(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,i]of Object.entries(e.headers))n.set(o,i)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new j(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);n.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new j(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new j("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new j("Response was set to base64 encoded but body was not a string",t.headers);r=bi(e.body)}else"body"in e&&typeof e.body=="string"?r=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?r=JSON.stringify(e.body):r=null;if(r!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new j(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:n,status:e.statusCode})}s(tc,"getResponse");async function nc(t,e,{useAwsResourcePathStyle:n}){let r={},o={};t.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let i=t.query,a={};for(let[l,d]of Object.entries(i))a[l]=[d];let u=new URL(t.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:t.method,headers:r,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:gr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:sc(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}s(nc,"buildEventVersion1");function rc(t,e){let n={};t.headers.forEach((i,a)=>{n[a]=i});let r=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:n,queryStringParameters:t.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:t.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:gr(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}s(rc,"buildEventVersion2");async function oc(t,{binaryMediaTypes:e}){let n,r=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")n=null;else if(e&&o&&ic(e,o)){let i=await t.arrayBuffer();n=Ri(new Uint8Array(i)),r=!0}else n=await t.clone().text();return[n,r]}s(oc,"getBodyResult");function ic(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}s(ic,"matchesContentType");function sc(t,e=!1){if(!e)return t;let n=cr(t),r=gi(t),o={};return n.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(sc,"getResourcePath");var ac=[502,503,504];async function De(t,e){if(ac.includes(t.status)){let n=A.getLogger(e),o=await t.clone().text(),i={};for(let[a,u]of t.headers)i[a]=u;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:i})}}s(De,"logBadGatewayResponses");var mr;function de(t){if(mr===void 0){let n=b.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),mr=n}return t.log[mr]}s(de,"getHandlerUserLogFunction");async function Oi(t,e){let n=b.instance.build.BUILD_ID,{buildAssetsUrl:r}=b.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new f("Open API Spec Handler must have 'openApiFilePath' specified");let a=uc(i);if(!a.isValid)throw new f(a.error);let u;b.instance.isLocalDevelopment?u=`${r}/${i.substring(1)}`:u=`${r}/${n}${i.substring(1)}`;let c=await fetch(u,{method:t.method,body:t.body,headers:t.headers});if(c.status!==200)return I.notFound(t,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return De(l,e),l}s(Oi,"openApiSpecHandler");var uc=s(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function vi(t,e){let n=e.route.handler.options;if(!n.location)throw new f("Redirect Handler must have 'location' specified");let r=n.status??302;return new Response(null,{status:r,headers:{location:n.location}})}s(vi,"redirectHandler");function cc(t,e){let n=t.endsWith("/"),r=e.startsWith("/");return n&&r?`${t.substring(0,t.length-1)}${e}`:!n&&!r?`${t}/${e}`:`${t}${e}`}s(cc,"join");async function Ti(t,e){let n=de(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),u=r.__rewriteFunction(t,i),c=cc(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();n(`URL Forwarding to '${l}'`);let p=await fetch(l,{method:t.method,body:t.body,headers:t.headers}),R=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${R}ms`),De(p,e),p}s(Ti,"urlForwardHandler");var lc=s((t,e)=>{let n=new URL(t),r=new URL(e);for(let[o,i]of r.searchParams.entries())n.searchParams.append(o,i);return n.toString()},"addQuery");async function Ci(t,e){let n=de(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=o?lc(u,t.url):u,l=Date.now();n(`URL Rewriting to '${c}'`);let d=await fetch(c.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:i?"follow":"manual"}),p=Date.now()-l;return n(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),De(d,e),d}s(Ci,"urlRewriteHandler");async function Ai(t,e){let n=b.instance,r=e.route.handler.options,o=de(e);if(!r||!r.rewritePattern)throw new f("WebSocket Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return I.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno){let p=new Headers(t.headers);if(u.startsWith("service:")){let m=await ui(u),y=new URL(u);u=new URL(`${m.serviceBaseUrl}${y.pathname}${y.search}`).toString();for(let w in m.tunnelHeaders)p.set(w,m.tunnelHeaders[w])}u=u.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let m=p.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${m}`}}catch{}let R=JSON.stringify({url:u});return new Response(R,{headers:p})}u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let p=await l.text(),R=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(R)}let d=Date.now()-c;return o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${d}ms`),new Response(null,{status:101,webSocket:l.webSocket})}s(Ai,"webSocketHandler");var fr=s((t,e)=>t.map((r,o)=>{let i;if(typeof r.module=="object"&&(i=r.module[r.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new f(`${a} - Websocket policy must be a valid function (${u})`)}return i}),"getWebSocketPolicyFunctions"),Li=s(async(t,e,n,r,o,i)=>{let a=t.data;if(i&&i.length>0){let u=[...i];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,n,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function Si(t,e,n,r,o){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",i=>{r.log.error("WebSocket error: ",i),e.send(JSON.stringify(i))}),t.addEventListener("message",i=>{try{s(async u=>{let c=await Li(u,t,e,n,r,o);c!==void 0&&e.send(c)},"innerPipeline")(i).catch(r.log.error)}catch(a){r.log.error(a)}})}s(Si,"wireUpListeners");async function _i(t,e){let n=b.instance,r=e.route.handler.options,o=de(e);if(!r||!r.rewritePattern)throw new f("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return I.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno)throw new f("Websocket pipeline handler is currently not supported on working-copy environments");u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let v=await l.text(),C=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${v}'`;throw new Error(C)}let d=new WebSocketPair,[p,R]=Object.values(d),m=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${m}ms`);let y=l.webSocket;y.accept(),R.accept();let P=r.policies&&r.policies.inbound?fr(r.policies.inbound,"inbound"):[],w=r.policies&&r.policies.outbound?fr(r.policies.outbound,"outbound"):[];return Si(R,y,t,e,P),Si(y,R,t,e,w),new Response(null,{status:101,webSocket:p})}s(_i,"webSocketPipelineHandler");var Bt=class extends H{constructor(n){super();this.options=n}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new hr(this.options)}},hr=class{static{s(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=b.instance.loggingEnvironmentType,this.#o=b.instance.loggingEnvironmentStage,this.#n=b.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:re(q(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new T("dyna-trace-log-transport",10,this.#i)};var zt=class extends H{constructor(n){super();this.options=n}static{s(this,"LokiLoggingPlugin")}getTransport(){return new br(this.options)}},yr=class{static{s(this,"LokiStream")}constructor(e,n,r,o,i){this.level=e,this.environment=n,this.environmentType=r,this.environmentStage=o,this.requestId=i}job="zuplo";level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function dc(t,e){return btoa(`${t}:${e}`)}s(dc,"createBasicDigest");var br=class{static{s(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=dc(e.username,e.password),this.#r=b.instance.loggingEnvironmentType,this.#o=b.instance.loggingEnvironmentStage,this.#n=b.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){let r=new yr(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let i={stream:r,message:re(q(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(i)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=e=>{let n={streams:[]};return e.forEach(r=>{let o=n.streams.find(i=>i.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},n.streams.push(o)),o.values.push([r.nanoSecondEpoch,r.message])}),n};#s=async e=>{if(e.length===0)return;let n=this.#i(e);await fetch(this.#e,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#t}`}})};batcher=new T("loki-log-transport",10,this.#s)};var Gt=class extends H{constructor(n){super();this.options=n}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new Rr(this.options)}},Rr=class{static{s(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=b.instance.loggingEnvironmentType,this.#r=b.instance.loggingEnvironmentStage,this.#t=b.instance.deploymentName}#e;#t;#n;#r;#o;#i;async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:re(q(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let n=e.map(o=>JSON.stringify(o)).join(`
61
61
  `),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await fetch(this.#e,{method:"POST",body:n,headers:r})};batcher=new T("sumo-logic-log-transport",10,this.#s)};var pc="d3a5b78f-8236-48f5-b1df-4fe269d41172",jt=class extends H{constructor(n){super();this.options=n}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new wr(this.options)}},wr=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){let n;try{n=new URL(e.url)}catch{throw new f(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=n.origin,this.#n=b.instance.loggingEnvironmentType,this.#r=b.instance.loggingEnvironmentStage,this.#t=b.instance.deploymentName,this.#o=e.onMessageSending,e.fields&&(this.#i=Object.entries(e.fields).map(([r,o])=>({name:r,content:o})))}#e;#t;#n;#r;#o;#i;async log(e,n){let r=this.buildEntry(e,n);this.batcher.enqueue(r),n.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,n){let r=Qo(e.messages),o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#n},{name:"environment_stage",content:this.#r},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#t&&o.fields.push({name:"environment",content:this.#t}),this.#i&&o.fields.push(...this.#i),n.custom&&Object.entries(n.custom).forEach(([i,a])=>{let u=Xn(a);u&&o.fields.push({name:i,content:u})}),this.#o&&(o=this.#o(o)),o}#s=async e=>{if(e.length===0)return;let n=await fetch(`${this.#e}/api/v1/events/ingest/${pc}`,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8"}});if(n.status!==200)try{let r=await n.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new T("vmware-log-insights-log-transport",10,this.#s)};var Jt=class extends H{constructor(n){super();this.options=n}static{s(this,"AWSLoggingPlugin")}getTransport(){return new Pr(this.options)}},Pr=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new T("aws-log-transport",10,async e=>{if(e.length===0)return;let n=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:n,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:n,logGroupName:r,secretAccessKey:o,region:i}){this.awsClient=new Se({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=n,this.region=i,this.environmentType=b.instance.loggingEnvironmentType,this.environment=b.instance.deploymentName}async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:re(q(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}};var Er=new WeakMap,gc={tags:[]},Kt=class extends ue{constructor(n){super();this.options=n}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new Ir(this.options)}static setContext(n,r){let o=Er.get(n);o||(o=gc);let i=Object.assign({...o},r);Er.set(n,i)}},Ir=class{static{s(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,n){this.#i===void 0&&(this.#i=new T("data-dog-metrics-transport",10,this.dispatchFunction,A.getLogger(n)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Er.get(n)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let i=e.systemRouteName||e.routePath;o.push(`path:${i}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),n.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=JSON.stringify({series:e}),r=await fetch(this.#t,{method:"POST",body:n,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new xr(await r.text())}},xr=class t extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Or=new WeakMap,mc={dimensions:[]},Wt=class extends ue{constructor(n){super();this.options=n}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new vr(this.options)}static setContext(n,r){let o=Or.get(n);o||(o=mc);let i=Object.assign({...o},r);Or.set(n,i)}},vr=class{static{s(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,n){this.#r===void 0&&(this.#r=new T("dynatrace-metrics-transport",10,this.dispatchFunction,A.getLogger(n)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Or.get(n)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let i=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${i} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${i} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${i} ${e.responseContentLength} ${r}`),n.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=e.join(`
62
- `),r=await fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new Tr(await r.text())}},Tr=class t extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Yt=class{static{s(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async n=>{await fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(n)})}))}};var Qt=class extends Be{static{s(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new Cr(e,this.#e,this.#t)}},Di=s(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),fc={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Cr=class{static{s(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...fc};r?.requestFilter&&(o.requestFilter=r.requestFilter),r?.include?.request&&Object.assign(o,r.include.request),r?.include?.response&&Object.assign(o,r.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new T("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,n,r,o,i,a)=>{try{let u={timestamp:o,durationMs:i,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:n.url,method:n.method,headers:this.#e.include?.request?.headers?Di(n.headers):void 0,body:this.#e.include?.request?.body?await n.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?Di(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}};#i=async(e,n)=>{try{if(!await this.#e.requestFilter(e,n))return e;let o=new Date,i=Date.now(),a=e.clone();return n.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,n,o,l-i,c.user?.sub).catch(R=>{n.log.error(R)});n.waitUntil(p)}),e}catch(r){return n.log.error(r),e}}};var Hi=new WeakMap,ki={},Xt=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Hi.set(e,n)}};async function Ui(t,e,n,r){if(!n.statusCodes)throw new f(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:Zo(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Hi.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new E(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=he(t.user,n.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},R=ki[n.apiKey];if(!R){let m=n.apiKey,y=t.headers.get("zm-test-id")??"";R=new T("amberflo-ingest-meter",10,async P=>{try{let w=n.url??"https://app.amberflo.io/ingest",v=await fetch(w,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":y}});v.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${v.status}: ${await v.text()}`)}catch(w){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${w.message}`),w}}),ki[m]=R}R.enqueue(p),e.waitUntil(R.waitUntilFlushed())}}),t}s(Ui,"AmberfloMeteringInboundPolicy");async function en(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(en,"sha256");var Ni=new Map;async function F(t,e){let n,r=Ni.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await en(JSON.stringify({policyName:t,options:e}))}`,Ni.set(t,n)),n}s(F,"getPolicyCacheName");var Mi="key-metadata-cache-type";function hc(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(hc,"getKeyValue");async function tn(t,e,n,r){if(!n.bucketName)if(rt.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=rt.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new f(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new f(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(w=>o.allowUnauthenticatedRequests?t:I.unauthorized(t,e,{detail:w}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=hc(a,o);if(!u||u==="")return i("No key present");let c=await yc(u),l=await F(r,o),d=new M(l,{logger:A.getLogger(e)}),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Mi&&A.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let R={key:u},m=await Te({retryDelayMs:5,retries:2,logger:A.getLogger(e)},`${b.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":b.instance.deploymentName??"unknown","User-Agent":b.instance.systemUserAgent},body:JSON.stringify(R)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(m.status!==200){try{let w=await m.text(),v=JSON.parse(w);e.log.error("Unexpected response from key service",v)}catch{e.log.error("Invalid response from key service")}throw new E(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let y=await m.json(),P={isValid:!0,typeId:Mi,user:{sub:y.name,data:y.metadata}};return t.user=P.user,d.put(c,P,o.cacheTtlSeconds),t}s(tn,"ApiKeyInboundPolicy");async function yc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(yc,"hashValue");var Zi=tn;var it=require("jose");var Ar={},bc=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new f("Invalid State - jwkUrl not set");Ar[e.jwkUrl]||(Ar[e.jwkUrl]=(0,it.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,it.jwtVerify)(t,Ar[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Rc=s(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);n=new Uint8Array(i)}else n=e.secret;let{payload:r}=await(0,it.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),N=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(R=>I.unauthorized(t,e,{detail:R}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?bc:Rc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let R=o.substring(i.length);if(!R||R.length===0)return a("No bearer token on authorization header");try{return await u(R,n)}catch(m){let y=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${y.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${y.pathname}`,m),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var qi=s(async(t,e,n,r)=>N(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Fi=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>I.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let R=d.substring(0,p),m=d.substring(p+1),y=n.accounts.find(P=>P.username===R&&P.password===m);return y||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var wc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Pc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Pc,"digestMessage");var Ec=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Pc(JSON.stringify(r)),i=new URL(t.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function $i(t,e,n,r){let o=await F(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Ec(t,n),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let R=n?.expirationSecondsTtl??60,m=new Response(p.body,p);wc.forEach(y=>m.headers.delete(y)),m.headers.set("cache-control",`s-maxage=${R}`),e.waitUntil(i.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s($i,"CachingInboundPolicy");var Vi=s(async(t,e,n,r)=>{if(!n.method)throw new f(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new _(t,{method:n.method})},"ChangeMethodInboundPolicy");var Bi=s(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new _(t,{headers:o})},"ClearHeadersInboundPolicy");var zi=s(async(t,e,n,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&i.set(u,c)}),new Response(t.body,{headers:i,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var Gi=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",N(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var ji=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new f("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new f("region must be set in the options for CognitoJwtInboundPolicy");return N(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var Ji=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new f(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=G.instance,i=Ke(n.policies,o?.routeData.policies);return Wn(i)(t,e)},"CompositeInboundPolicy");function $(t,e){let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new f(`Value of '${String(i)}' on policy '${e}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(c))throw new f(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new f(`Value of '${String(i)}' on policy '${e}' must be of type ${a}. Received type ${typeof c}.`);if(typeof c=="string"&&c.length===0)throw new f(`Value of '${String(i)}' on policy '${e}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof c=="number"&&isNaN(c))throw new f(`Value of '${String(i)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),r=s((i,a)=>(n(i,a,!0),{optional:r,required:o}),"optional"),o=s((i,a)=>(n(i,a,!1),{optional:r,required:o}),"required");return{optional:r,required:o}}s($,"optionValidator");var Ki=s(async(t,e,n,r)=>($(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),N(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Wi=s(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=t.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new _(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var ke="__unknown__",Yi=s(async(t,e,n,r)=>{let o={allow:{countries:Ue(n.allow?.countries,"allow.countries",r),regionCodes:Ue(n.allow?.regionCodes,"allow.regionCode",r),asns:Ue(n.allow?.asns,"allow.asOrganization",r)},block:{countries:Ue(n.block?.countries,"block.countries",r),regionCodes:Ue(n.block?.regionCodes,"block.regionCode",r),asns:Ue(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??ke,a=e.incomingRequestProperties.regionCode?.toLowerCase()??ke,u=e.incomingRequestProperties.asn?.toString()??ke,c=o.ignoreUnknown&&i===ke,l=o.ignoreUnknown&&a===ke,d=o.ignoreUnknown&&u===ke,p=o.allow.countries,R=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||R.length>0&&!R.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return He(t,e,r,i,a,u);let y=o.block.countries,P=o.block.regionCodes,w=o.block.asns;return y.length>0&&y.includes(i)&&!c||P.length>0&&P.includes(a)&&!l||w.length>0&&w.includes(u)&&!d?He(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function He(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),I.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(He,"blockedResponse");function Ue(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new f(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(Ue,"toLowerStringArray");var Qi=s(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,n.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var es=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Lr(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return Lr(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(R=>{a.push({responseName:u,contentName:l,exampleName:R,exampleValue:d[R]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Xi(a[u])}else return a.length>0?Xi(a[0]):Lr(r,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function Xi(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}s(Xi,"generateResponse");var Lr=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return I.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var Ic="Incoming",xc={logRequestBody:!0,logResponseBody:!0};function ts(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(ts,"headersToObject");function ns(){return new Date().toISOString()}s(ns,"timestamp");var Sr=new WeakMap,Oc={};function is(t,e){let n=Sr.get(t);n||(n=Oc);let r=Object.assign({...n},e);Sr.set(t,r)}s(is,"setMoesifContext");async function rs(t,e){let n=t.headers.get("content-type"),r=t.clone();if(n&&n.indexOf("json")!==0)try{return await r.json()}catch(i){e.log.error(i)}let o=await r.text();return e.log.debug({textBody:o}),o}s(rs,"readBody");var vc={},_r;function os(){if(!_r)throw new E("Invalid State - no _lastLogger");return _r}s(os,"getLastLogger");function Tc(t){let e=vc[t];return e||(e=new T("moesif-inbound",100,async n=>{let r=JSON.stringify(n);os().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||os().error({status:o.status,body:await o.text()})})),e}s(Tc,"getDispatcher");async function ss(t,e,n,r){_r=e.log;let o=ns(),i=Object.assign(xc,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await rs(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Tc(i.applicationId),d=t.headers.get("true-client-ip"),p=Sr.get(e)??{},R={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:ts(t.headers)},m=i.logResponseBody?await rs(u,e):void 0,y={time:ns(),status:u.status,headers:ts(u.headers),body:m},P={request:R,response:y,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Ic};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),t}s(ss,"MoesifInboundPolicy");var as=s(async(t,e,n,r)=>N(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var us=require("jose");var Dr,cs=s(async(t,e,n,r)=>{if(!Dr)try{Dr=await(0,us.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return N(t,e,{issuer:n.authUrl,secret:Dr,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ds=we(me());var nn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},kr=class extends nn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Hr=class extends nn{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function Cc(t,e){if(No(t))throw new kr(e)}s(Cc,"throwIfUndefinedOrNull");function st(t,e){if(Cc(t,e),!ce(t))throw new Hr(e,"string")}s(st,"throwIfNotString");var rn=class t{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return st(e,"redisClientUrl"),st(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){st(e,"url");let i=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new S("Redis client failed with 401: Unauthorized"):new S(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},on=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(st(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(n),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new S("The in-memory redis client only supports /rate-limit calls")}};var sn=(0,ds.debug)("zuplo:policies:RateLimitInboundPolicy"),Ac="strict",Lc=s(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),Sc=s(async t=>({key:`ip-${Lc(t)}`}),"getIP"),_c=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),Dc=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),an;function kc(t,e){let n;if(an)return an;if(b.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new on,an=n,n;let{authApiJWT:r,redisURL:o}=b.instance;if(!ce(o))throw new S(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!ce(r))throw new S(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=rn.initialize(o,r,b.instance.deploymentName??"unknown",b.instance.systemUserAgent)),!n||!n.isEnabled())throw new S(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return an=n,n}s(kc,"getRedisClient");async function ls(t,e,n,r,o){let i=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:t}),requestId:o})}s(ls,"getCountAndUpdateExpiry");function Hc(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new f(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new E(c)}return u},"outerFunction")}s(Hc,"wrapUserFunction");var Uc="Retry-After",Ur=s(async(t,e,n,r)=>{let o=Date.now(),i=A.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new S(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Uc]=l.toString()),I.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:Hc(n,r),user:_c,ip:Sc,all:Dc}[n.rateLimitBy],d=await l(t,e,r),p=d.key,R=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,y=n.headerMode??"retry-after",P=kc(r,i),v=`bucket/${b.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??Ac)==="async"){let L=await F(r,n),V=new oe(L,{logger:A.getLogger(e)}),J=ls(v,m,P,i,e.requestId),K=await V.get(v);if(K!==void 0&&K<=Date.now()){sn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${v}' (async mode)`);let be=Math.round((K-Date.now())/1e3);return u(y,be)}return e.addEventListener("responseSending",be=>{try{let Re=be,hn=Re.mutableResponse;Re.mutableResponse=(async()=>{let at=await J;if(at.count>R){let Bs=Date.now()+at.ttlSeconds*1e3;return V.put(v,Bs,at.ttlSeconds).catch(zr=>{throw i.error(zr),zr}),sn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${v}' (async mode)`),u(y,at.ttlSeconds)}return hn})()}catch(Re){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,Re)}}),t}let D=await ls(v,m,P,i,e.requestId);return D.count>R?(sn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${v}' (strict mode)`),u(y,D.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;sn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var Nr;function ps(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(ps,"headersToNameValuePairs");function Nc(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(Nc,"queryToNameValueParis");function Mc(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(Mc,"parseIntOrUndefined");var gs={};async function ms(t,e,n,r){let o=new Date,i=Date.now();return Nr||(Nr={name:"zuplo",version:b.instance.build.ZUPLO_VERSION,comment:`zuplo/${b.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?he(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?he(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:b.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Nr,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:ps(t.headers),queryString:Nc(t.query)},response:{status:a.status,statusText:a.statusText,headers:ps(a.headers),content:{size:Mc(t.headers.get("content-length"))}}}]}}},d=gs[n.apiKey];if(!d){let p=n.apiKey;d=new T("readme-metering-inbound-policy",10,async R=>{try{let m=n.url??"https://metrics.readme.io/request",y=await fetch(m,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${y.status}: '${await y.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),gs[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(ms,"ReadmeMetricsInboundPolicy");var fs=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new _(t,{headers:i})},"RemoveHeadersInboundPolicy");var hs=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new f(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return i.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var ys=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new _(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var bs=s(async(t,e,n,r)=>{let o=await t.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var Rs=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),ws=s(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>n.maxSizeInBytes?Rs():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?Rs():t},"RequestSizeLimitInboundPolicy");function Ps(t,e,n){return`_${pe(t+"_"+e+"_"+n)}`}s(Ps,"getRawOperationDataIdentifierName");function un(t,e,n,r){return`_${pe(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(un,"getIdForParameterSchema");function cn(t,e,n){return`_${pe(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${pe(n.toLowerCase())}`}s(cn,"getIdForRequestBodySchema");function Es(t,e){return`_${pe(t)}__${pe(e)}`}s(Es,"getIdForRefSchema");function pe(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}s(pe,"sanitizedIdentifierName");var Ne=s(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),Me=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{if(c.required&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else{let l=un(n,r,o,c.name),d=G.instance.schemaValidator[l],p=d(e[c.name]),R=Mr(d.errors);p||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${R.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),Y=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),Q=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),X=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),Mr=s(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Is(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let y=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=I.badRequest(e,t,{detail:`${y}, see errors property for more details`,errors:`${m}`});if(Q(n.validateBody)&&Y(t,n.logLevel??"info",y,[r],m),X(n.validateBody))return P}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,y=I.badRequest(e,t,{detail:m});return Q(n.validateBody)&&Y(t,n.logLevel??"info",m,[r],[m]),X(n.validateBody)?y:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=cn(t.route.path,e.method,o),u=G.instance.schemaValidator[a];if(!u){let m=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,y=I.badRequest(e,t,{detail:m});return Q(n.validateBody)&&Y(t,n.logLevel??"info",m,[r],[m]),X(n.validateBody)?y:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Mr(l),R=I.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(Q(n.validateBody)&&Y(t,n.logLevel??"info",d,[r],p),X(n.validateBody))return R}s(Is,"handleBodyValidation");function xs(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Ne(t),i=Me(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=I.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(Q(n.validateHeaders)&&Y(t,n.logLevel??"info",a,i.invalidValues,i.errors),X(n.validateHeaders))return u}}s(xs,"handleHeadersValidation");function Os(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=Ne(t),o=Me(r.filter(i=>i.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=I.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Q(n.validatePathParameters)&&Y(t,n.logLevel??"info",i,o.invalidValues,o.errors),X(n.validatePathParameters))return a}}s(Os,"handlePathParameterValidation");function vs(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=Ne(t),o=Me(r.filter(i=>i.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=I.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Q(n.validateQueryParameters)&&Y(t,n.logLevel??"info",i,o.invalidValues,o.errors),X(n.validateQueryParameters))return a}}s(vs,"handleQueryParameterValidation");var Zr=s(async(t,e,n)=>{let r=vs(e,t,n);if(r!==void 0||(r=Os(e,t,n),r!==void 0)||(r=xs(e,t,n),r!==void 0))return r;let o=await Is(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Ts=Zr;var Cs=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new f(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let i=t.headers.get("origin");if(!i||!o.includes(i)){let a=n.failureDetail??"Forbidden";return I.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var As=s(async(t,e,n)=>new _(t,{body:n.body}),"SetBodyInboundPolicy");var Ls=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new _(t,{headers:i})},"SetHeadersInboundPolicy");var Ss=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new f(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new f(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var _s=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new _(i.toString(),t)},"SetQueryParamsInboundPolicy");var Ds=s(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var Zc=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),ks=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new f(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Zc(n.sleepInMs),t},"SleepInboundPolicy");var Hs=s(async(t,e,n,r)=>{$(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await N(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof _))throw new S("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new E(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?I.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var Us=s(async(t,e,n,r)=>{$(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await F(r,n),i=new M(o,{logger:A.getLogger(e)}),a=await i.get(r);if(!a){let u=await qc(n,e);i.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function qc(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Te({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new E("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new E("Response returned from Azure AD is not in the expected format.")}s(qc,"getAccessToken");var Ns="https://accounts.google.com/o/oauth2/token",qr,Ms=s(async(t,e,n,r)=>{$(n,r).required("serviceAccountJson","string"),qr||(qr=await z.init(n.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await F(r,n),a=new M(i,{logger:A.getLogger(e)}),u=await a.get(r);if(!u){let c=await ee({serviceAccount:qr,audience:Ns,payload:o}),l=await At(Ns,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new E("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var Fc="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",$c=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Fr,Zs=s(async(t,e,n,r)=>{if($(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new f(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if($c.indexOf(p)!==-1)throw new f(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}Fr||(Fr=await z.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new E("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new E(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=he(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new E(`Unable to determine user from for the policy ${r}`);let a=await F(r,n),u=new M(a,{logger:A.getLogger(e)}),c={uid:i,claims:o},l=await en(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await ee({serviceAccount:Fr,audience:Fc,payload:c}),R=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await Xo(R,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new E("Invalid token response from Firebase");d=m.idToken,u.put(l,d,(m.expiresIn?parseInt(m.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var $r,qs=s(async(t,e,n,r)=>{$(n,r).required("audience","string").required("serviceAccountJson","string"),$r||($r=await z.init(n.serviceAccountJson));let o=await ee({serviceAccount:$r,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Fs="https://www.googleapis.com/oauth2/v4/token",Vr,$s=s(async(t,e,n,r)=>{$(n,r).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Vr||(Vr=await z.init(n.serviceAccountJson));let o=await F(r,n),i;n.useMemoryCacheOnly?i=new Pe(o):i=new M(o,e);let a=await i.get(r);if(!a){let u=await ee({serviceAccount:Vr,audience:Fs,payload:{target_audience:`${n.audience}`}}),{id_token:c}=await At(Fs,u,{retries:n.tokenRetries??3,retryDelayMs:10});if(!c)throw new E("Invalid token response from GCP");a=c,i.put(r,a,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamGcpServiceAuthInboundPolicy");var Vs=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return I.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new S("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return I.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ln={Json:"application/json",Form:"application/x-www-form-urlencoded"};function yt(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(ln.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(ln.Json)||!e?JSON.stringify(t):t}s(yt,"serialize");var dn=class t{static{s(this,"ServiceProviderImpl")}static#e;services=new Map;constructor(){}static getInstance(){return t.#e||(t.#e=new t),t.#e}setInstance(e){t.#e=e}addService(e,n){if(this.services.get(e))throw new S(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var Vc={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},wt=Vc;var Br=["sha-1","sha-256","sha-384","sha-512"],pn=class{static{s(this,"BaseCryptoBeta")}};var gn=class extends pn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!Br.includes(e.toLowerCase()))throw new E(`Algorithm ${e} is not supported. Try using ${Br.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var mn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var fn=class extends mn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new ut("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new f("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
62
+ `),r=await fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new Tr(await r.text())}},Tr=class t extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Yt=class{static{s(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async n=>{await fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(n)})}))}};var Qt=class extends Be{static{s(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new Cr(e,this.#e,this.#t)}},Di=s(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),fc={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Cr=class{static{s(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...fc};r?.requestFilter&&(o.requestFilter=r.requestFilter),r?.include?.request&&Object.assign(o,r.include.request),r?.include?.response&&Object.assign(o,r.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new T("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,n,r,o,i,a)=>{try{let u={timestamp:o,durationMs:i,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:n.url,method:n.method,headers:this.#e.include?.request?.headers?Di(n.headers):void 0,body:this.#e.include?.request?.body?await n.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?Di(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}};#i=async(e,n)=>{try{if(!await this.#e.requestFilter(e,n))return e;let o=new Date,i=Date.now(),a=e.clone();return n.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,n,o,l-i,c.user?.sub).catch(R=>{n.log.error(R)});n.waitUntil(p)}),e}catch(r){return n.log.error(r),e}}};var Hi=new WeakMap,ki={},Xt=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Hi.set(e,n)}};async function Ui(t,e,n,r){if(!n.statusCodes)throw new f(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:Zo(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Hi.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new E(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=he(t.user,n.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},R=ki[n.apiKey];if(!R){let m=n.apiKey,y=t.headers.get("zm-test-id")??"";R=new T("amberflo-ingest-meter",10,async P=>{try{let w=n.url??"https://app.amberflo.io/ingest",v=await fetch(w,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":y}});v.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${v.status}: ${await v.text()}`)}catch(w){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${w.message}`),w}}),ki[m]=R}R.enqueue(p),e.waitUntil(R.waitUntilFlushed())}}),t}s(Ui,"AmberfloMeteringInboundPolicy");async function en(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(en,"sha256");var Ni=new Map;async function F(t,e){let n,r=Ni.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await en(JSON.stringify({policyName:t,options:e}))}`,Ni.set(t,n)),n}s(F,"getPolicyCacheName");var Mi="key-metadata-cache-type";function hc(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(hc,"getKeyValue");async function tn(t,e,n,r){if(!n.bucketName)if(rt.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=rt.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new f(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new f(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(w=>o.allowUnauthenticatedRequests?t:I.unauthorized(t,e,{detail:w}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=hc(a,o);if(!u||u==="")return i("No key present");let c=await yc(u),l=await F(r,o),d=new M(l,{logger:A.getLogger(e)}),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Mi&&A.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let R={key:u},m=await Te({retryDelayMs:5,retries:2,logger:A.getLogger(e)},`${b.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":b.instance.deploymentName??"unknown","User-Agent":b.instance.systemUserAgent},body:JSON.stringify(R)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(m.status!==200){try{let w=await m.text(),v=JSON.parse(w);e.log.error("Unexpected response from key service",v)}catch{e.log.error("Invalid response from key service")}throw new E(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let y=await m.json(),P={isValid:!0,typeId:Mi,user:{sub:y.name,data:y.metadata}};return t.user=P.user,d.put(c,P,o.cacheTtlSeconds),t}s(tn,"ApiKeyInboundPolicy");async function yc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(yc,"hashValue");var Zi=tn;var it=require("jose");var Ar={},bc=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new f("Invalid State - jwkUrl not set");Ar[e.jwkUrl]||(Ar[e.jwkUrl]=(0,it.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,it.jwtVerify)(t,Ar[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Rc=s(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);n=new Uint8Array(i)}else n=e.secret;let{payload:r}=await(0,it.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),N=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(R=>I.unauthorized(t,e,{detail:R}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?bc:Rc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let R=o.substring(i.length);if(!R||R.length===0)return a("No bearer token on authorization header");try{return await u(R,n)}catch(m){let y=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${y.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${y.pathname}`,m),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var qi=s(async(t,e,n,r)=>N(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Fi=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>I.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let R=d.substring(0,p),m=d.substring(p+1),y=n.accounts.find(P=>P.username===R&&P.password===m);return y||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var wc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Pc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Pc,"digestMessage");var Ec=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Pc(JSON.stringify(r)),i=new URL(t.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function $i(t,e,n,r){let o=await F(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Ec(t,n),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let R=n?.expirationSecondsTtl??60,m=new Response(p.body,p);wc.forEach(y=>m.headers.delete(y)),m.headers.set("cache-control",`s-maxage=${R}`),e.waitUntil(i.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s($i,"CachingInboundPolicy");var Vi=s(async(t,e,n,r)=>{if(!n.method)throw new f(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new _(t,{method:n.method})},"ChangeMethodInboundPolicy");var Bi=s(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new _(t,{headers:o})},"ClearHeadersInboundPolicy");var zi=s(async(t,e,n,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&i.set(u,c)}),new Response(t.body,{headers:i,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var Gi=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",N(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var ji=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new f("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new f("region must be set in the options for CognitoJwtInboundPolicy");return N(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var Ji=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new f(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=G.instance,i=Ke(n.policies,o?.routeData.policies);return Wn(i)(t,e)},"CompositeInboundPolicy");function $(t,e){let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new f(`Value of '${String(i)}' on policy '${e}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(c))throw new f(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new f(`Value of '${String(i)}' on policy '${e}' must be of type ${a}. Received type ${typeof c}.`);if(typeof c=="string"&&c.length===0)throw new f(`Value of '${String(i)}' on policy '${e}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof c=="number"&&isNaN(c))throw new f(`Value of '${String(i)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),r=s((i,a)=>(n(i,a,!0),{optional:r,required:o}),"optional"),o=s((i,a)=>(n(i,a,!1),{optional:r,required:o}),"required");return{optional:r,required:o}}s($,"optionValidator");var Ki=s(async(t,e,n,r)=>($(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),N(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Wi=s(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=t.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new _(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var ke="__unknown__",Yi=s(async(t,e,n,r)=>{let o={allow:{countries:Ue(n.allow?.countries,"allow.countries",r),regionCodes:Ue(n.allow?.regionCodes,"allow.regionCode",r),asns:Ue(n.allow?.asns,"allow.asOrganization",r)},block:{countries:Ue(n.block?.countries,"block.countries",r),regionCodes:Ue(n.block?.regionCodes,"block.regionCode",r),asns:Ue(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??ke,a=e.incomingRequestProperties.regionCode?.toLowerCase()??ke,u=e.incomingRequestProperties.asn?.toString()??ke,c=o.ignoreUnknown&&i===ke,l=o.ignoreUnknown&&a===ke,d=o.ignoreUnknown&&u===ke,p=o.allow.countries,R=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||R.length>0&&!R.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return He(t,e,r,i,a,u);let y=o.block.countries,P=o.block.regionCodes,w=o.block.asns;return y.length>0&&y.includes(i)&&!c||P.length>0&&P.includes(a)&&!l||w.length>0&&w.includes(u)&&!d?He(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function He(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),I.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(He,"blockedResponse");function Ue(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new f(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(Ue,"toLowerStringArray");var Qi=s(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,n.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var es=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Lr(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return Lr(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(R=>{a.push({responseName:u,contentName:l,exampleName:R,exampleValue:d[R]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Xi(a[u])}else return a.length>0?Xi(a[0]):Lr(r,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function Xi(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}s(Xi,"generateResponse");var Lr=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return I.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var Ic="Incoming",xc={logRequestBody:!0,logResponseBody:!0};function ts(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(ts,"headersToObject");function ns(){return new Date().toISOString()}s(ns,"timestamp");var Sr=new WeakMap,Oc={};function is(t,e){let n=Sr.get(t);n||(n=Oc);let r=Object.assign({...n},e);Sr.set(t,r)}s(is,"setMoesifContext");async function rs(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}s(rs,"readBody");var vc={},_r;function os(){if(!_r)throw new E("Invalid State - no _lastLogger");return _r}s(os,"getLastLogger");function Tc(t){let e=vc[t];return e||(e=new T("moesif-inbound",100,async n=>{let r=JSON.stringify(n);os().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||os().error({status:o.status,body:await o.text()})})),e}s(Tc,"getDispatcher");async function ss(t,e,n,r){_r=e.log;let o=ns(),i=Object.assign(xc,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await rs(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Tc(i.applicationId),d=t.headers.get("true-client-ip"),p=Sr.get(e)??{},R={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:ts(t.headers)},m=i.logResponseBody?await rs(u,e):void 0,y={time:ns(),status:u.status,headers:ts(u.headers),body:m},P={request:R,response:y,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Ic};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),t}s(ss,"MoesifInboundPolicy");var as=s(async(t,e,n,r)=>N(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var us=require("jose");var Dr,cs=s(async(t,e,n,r)=>{if(!Dr)try{Dr=await(0,us.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return N(t,e,{issuer:n.authUrl,secret:Dr,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ds=we(me());var nn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},kr=class extends nn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Hr=class extends nn{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function Cc(t,e){if(No(t))throw new kr(e)}s(Cc,"throwIfUndefinedOrNull");function st(t,e){if(Cc(t,e),!ce(t))throw new Hr(e,"string")}s(st,"throwIfNotString");var rn=class t{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return st(e,"redisClientUrl"),st(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){st(e,"url");let i=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new S("Redis client failed with 401: Unauthorized"):new S(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},on=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(st(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(n),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new S("The in-memory redis client only supports /rate-limit calls")}};var sn=(0,ds.debug)("zuplo:policies:RateLimitInboundPolicy"),Ac="strict",Lc=s(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),Sc=s(async t=>({key:`ip-${Lc(t)}`}),"getIP"),_c=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),Dc=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),an;function kc(t,e){let n;if(an)return an;if(b.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new on,an=n,n;let{authApiJWT:r,redisURL:o}=b.instance;if(!ce(o))throw new S(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!ce(r))throw new S(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=rn.initialize(o,r,b.instance.deploymentName??"unknown",b.instance.systemUserAgent)),!n||!n.isEnabled())throw new S(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return an=n,n}s(kc,"getRedisClient");async function ls(t,e,n,r,o){let i=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:t}),requestId:o})}s(ls,"getCountAndUpdateExpiry");function Hc(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new f(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new E(c)}return u},"outerFunction")}s(Hc,"wrapUserFunction");var Uc="Retry-After",Ur=s(async(t,e,n,r)=>{let o=Date.now(),i=A.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new S(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Uc]=l.toString()),I.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:Hc(n,r),user:_c,ip:Sc,all:Dc}[n.rateLimitBy],d=await l(t,e,r),p=d.key,R=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,y=n.headerMode??"retry-after",P=kc(r,i),v=`bucket/${b.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??Ac)==="async"){let L=await F(r,n),V=new oe(L,{logger:A.getLogger(e)}),J=ls(v,m,P,i,e.requestId),K=await V.get(v);if(K!==void 0&&K<=Date.now()){sn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${v}' (async mode)`);let be=Math.round((K-Date.now())/1e3);return u(y,be)}return e.addEventListener("responseSending",be=>{try{let Re=be,hn=Re.mutableResponse;Re.mutableResponse=(async()=>{let at=await J;if(at.count>R){let Bs=Date.now()+at.ttlSeconds*1e3;return V.put(v,Bs,at.ttlSeconds).catch(zr=>{throw i.error(zr),zr}),sn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${v}' (async mode)`),u(y,at.ttlSeconds)}return hn})()}catch(Re){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,Re)}}),t}let D=await ls(v,m,P,i,e.requestId);return D.count>R?(sn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${v}' (strict mode)`),u(y,D.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;sn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var Nr;function ps(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(ps,"headersToNameValuePairs");function Nc(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(Nc,"queryToNameValueParis");function Mc(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(Mc,"parseIntOrUndefined");var gs={};async function ms(t,e,n,r){let o=new Date,i=Date.now();return Nr||(Nr={name:"zuplo",version:b.instance.build.ZUPLO_VERSION,comment:`zuplo/${b.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?he(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?he(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:b.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Nr,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:ps(t.headers),queryString:Nc(t.query)},response:{status:a.status,statusText:a.statusText,headers:ps(a.headers),content:{size:Mc(t.headers.get("content-length"))}}}]}}},d=gs[n.apiKey];if(!d){let p=n.apiKey;d=new T("readme-metering-inbound-policy",10,async R=>{try{let m=n.url??"https://metrics.readme.io/request",y=await fetch(m,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${y.status}: '${await y.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),gs[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(ms,"ReadmeMetricsInboundPolicy");var fs=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new _(t,{headers:i})},"RemoveHeadersInboundPolicy");var hs=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new f(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return i.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var ys=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new _(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var bs=s(async(t,e,n,r)=>{let o=await t.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var Rs=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),ws=s(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>n.maxSizeInBytes?Rs():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?Rs():t},"RequestSizeLimitInboundPolicy");function Ps(t,e,n){return`_${pe(t+"_"+e+"_"+n)}`}s(Ps,"getRawOperationDataIdentifierName");function un(t,e,n,r){return`_${pe(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(un,"getIdForParameterSchema");function cn(t,e,n){return`_${pe(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${pe(n.toLowerCase())}`}s(cn,"getIdForRequestBodySchema");function Es(t,e){return`_${pe(t)}__${pe(e)}`}s(Es,"getIdForRefSchema");function pe(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}s(pe,"sanitizedIdentifierName");var Ne=s(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),Me=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{if(c.required&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else{let l=un(n,r,o,c.name),d=G.instance.schemaValidator[l],p=d(e[c.name]),R=Mr(d.errors);p||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${R.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),Y=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),Q=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),X=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),Mr=s(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Is(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let y=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=I.badRequest(e,t,{detail:`${y}, see errors property for more details`,errors:`${m}`});if(Q(n.validateBody)&&Y(t,n.logLevel??"info",y,[r],m),X(n.validateBody))return P}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,y=I.badRequest(e,t,{detail:m});return Q(n.validateBody)&&Y(t,n.logLevel??"info",m,[r],[m]),X(n.validateBody)?y:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=cn(t.route.path,e.method,o),u=G.instance.schemaValidator[a];if(!u){let m=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,y=I.badRequest(e,t,{detail:m});return Q(n.validateBody)&&Y(t,n.logLevel??"info",m,[r],[m]),X(n.validateBody)?y:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Mr(l),R=I.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(Q(n.validateBody)&&Y(t,n.logLevel??"info",d,[r],p),X(n.validateBody))return R}s(Is,"handleBodyValidation");function xs(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Ne(t),i=Me(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=I.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(Q(n.validateHeaders)&&Y(t,n.logLevel??"info",a,i.invalidValues,i.errors),X(n.validateHeaders))return u}}s(xs,"handleHeadersValidation");function Os(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=Ne(t),o=Me(r.filter(i=>i.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=I.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Q(n.validatePathParameters)&&Y(t,n.logLevel??"info",i,o.invalidValues,o.errors),X(n.validatePathParameters))return a}}s(Os,"handlePathParameterValidation");function vs(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=Ne(t),o=Me(r.filter(i=>i.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=I.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Q(n.validateQueryParameters)&&Y(t,n.logLevel??"info",i,o.invalidValues,o.errors),X(n.validateQueryParameters))return a}}s(vs,"handleQueryParameterValidation");var Zr=s(async(t,e,n)=>{let r=vs(e,t,n);if(r!==void 0||(r=Os(e,t,n),r!==void 0)||(r=xs(e,t,n),r!==void 0))return r;let o=await Is(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Ts=Zr;var Cs=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new f(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let i=t.headers.get("origin");if(!i||!o.includes(i)){let a=n.failureDetail??"Forbidden";return I.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var As=s(async(t,e,n)=>new _(t,{body:n.body}),"SetBodyInboundPolicy");var Ls=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new _(t,{headers:i})},"SetHeadersInboundPolicy");var Ss=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new f(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new f(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var _s=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new _(i.toString(),t)},"SetQueryParamsInboundPolicy");var Ds=s(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var Zc=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),ks=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new f(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Zc(n.sleepInMs),t},"SleepInboundPolicy");var Hs=s(async(t,e,n,r)=>{$(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await N(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof _))throw new S("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new E(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?I.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var Us=s(async(t,e,n,r)=>{$(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await F(r,n),i=new M(o,{logger:A.getLogger(e)}),a=await i.get(r);if(!a){let u=await qc(n,e);i.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function qc(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Te({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new E("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new E("Response returned from Azure AD is not in the expected format.")}s(qc,"getAccessToken");var Ns="https://accounts.google.com/o/oauth2/token",qr,Ms=s(async(t,e,n,r)=>{$(n,r).required("serviceAccountJson","string"),qr||(qr=await z.init(n.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await F(r,n),a=new M(i,{logger:A.getLogger(e)}),u=await a.get(r);if(!u){let c=await ee({serviceAccount:qr,audience:Ns,payload:o}),l=await At(Ns,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new E("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var Fc="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",$c=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Fr,Zs=s(async(t,e,n,r)=>{if($(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new f(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if($c.indexOf(p)!==-1)throw new f(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}Fr||(Fr=await z.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new E("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new E(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=he(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new E(`Unable to determine user from for the policy ${r}`);let a=await F(r,n),u=new M(a,{logger:A.getLogger(e)}),c={uid:i,claims:o},l=await en(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await ee({serviceAccount:Fr,audience:Fc,payload:c}),R=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await Xo(R,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new E("Invalid token response from Firebase");d=m.idToken,u.put(l,d,(m.expiresIn?parseInt(m.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var $r,qs=s(async(t,e,n,r)=>{$(n,r).required("audience","string").required("serviceAccountJson","string"),$r||($r=await z.init(n.serviceAccountJson));let o=await ee({serviceAccount:$r,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Fs="https://www.googleapis.com/oauth2/v4/token",Vr,$s=s(async(t,e,n,r)=>{$(n,r).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Vr||(Vr=await z.init(n.serviceAccountJson));let o=await F(r,n),i;n.useMemoryCacheOnly?i=new Pe(o):i=new M(o,e);let a=await i.get(r);if(!a){let u=await ee({serviceAccount:Vr,audience:Fs,payload:{target_audience:`${n.audience}`}}),{id_token:c}=await At(Fs,u,{retries:n.tokenRetries??3,retryDelayMs:10});if(!c)throw new E("Invalid token response from GCP");a=c,i.put(r,a,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamGcpServiceAuthInboundPolicy");var Vs=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return I.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new S("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return I.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ln={Json:"application/json",Form:"application/x-www-form-urlencoded"};function yt(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(ln.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(ln.Json)||!e?JSON.stringify(t):t}s(yt,"serialize");var dn=class t{static{s(this,"ServiceProviderImpl")}static#e;services=new Map;constructor(){}static getInstance(){return t.#e||(t.#e=new t),t.#e}setInstance(e){t.#e=e}addService(e,n){if(this.services.get(e))throw new S(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var Vc={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},wt=Vc;var Br=["sha-1","sha-256","sha-384","sha-512"],pn=class{static{s(this,"BaseCryptoBeta")}};var gn=class extends pn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!Br.includes(e.toLowerCase()))throw new E(`Algorithm ${e} is not supported. Try using ${Br.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var mn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var fn=class extends mn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new ut("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new f("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
63
63
  /*! For license information please see index.minified.js.LEGAL.txt */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
- "version": "5.1586.0",
3
+ "version": "5.1588.0",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "exports": {