/**
 * A high-level client for signing and sending AWS requests with Signature
 * Version 4. API-compatible with aws4fetch, with the addition of the
 * `credentials` provider option and the {@link AwsClient.fromContext} helper.
 *
 * @beta
 * @example
 * ```typescript
 * import { AwsClient } from "@zuplo/runtime/aws";
 *
 * const aws = new AwsClient({
 *   accessKeyId: environment.AWS_ACCESS_KEY_ID,
 *   secretAccessKey: environment.AWS_SECRET_ACCESS_KEY,
 *   region: "us-east-1",
 * });
 * const response = await aws.fetch(
 *   "https://s3.us-east-1.amazonaws.com/my-bucket/key"
 * );
 * ```
 */
export declare class AwsClient {
  #private;
  service?: string;
  region?: string;
  cache: Map<string, ArrayBuffer>;
  constructor(options: AwsClientOptions);
  /**
   * Creates an {@link AwsClient} from the credential provider registered on the
   * request context by an upstream AWS auth policy (`upstream-aws-service-auth`
   * or `upstream-aws-federated-auth`).
   *
   * @beta
   * @param context - The current ZuploContext
   * @param options - Optional service/region overrides for signing
   * @throws A ConfigurationError if no upstream AWS auth policy has run on this
   * route.
   * @example
   * ```typescript
   * import { AwsClient } from "@zuplo/runtime/aws";
   *
   * export default async function (request: ZuploRequest, context: ZuploContext) {
   *   const aws = AwsClient.fromContext(context);
   *   return aws.fetch("https://abc.execute-api.us-east-1.amazonaws.com/prod/thing");
   * }
   * ```
   */
  static fromContext(
    context: ZuploContext,
    options?: {
      service?: string;
      region?: string;
    }
  ): AwsClient;
  sign(
    url: string,
    init?: AwsRequestInit
  ): Promise<{
    url: string;
    request: AwsRequestInit & {
      method: string;
      url: URL;
      headers: Headers;
      body?: BodyInit | null;
    };
  }>;
  fetch(url: string, init?: AwsRequestInit): Promise<Response>;
}

/**
 * Options for constructing an {@link AwsClient}.
 *
 * Provide credentials in exactly one of two ways: the legacy inline
 * `accessKeyId`/`secretAccessKey` fields (aws4fetch-compatible), or a
 * `credentials` object/provider. When both are present, `credentials` wins.
 *
 * @beta
 */
export declare interface AwsClientOptions {
  /**
   * Static AWS access key ID. Prefer `credentials` for anything other than a
   * fixed IAM user key.
   */
  accessKeyId?: string;
  /**
   * Static AWS secret access key.
   */
  secretAccessKey?: string;
  /**
   * Static AWS session token, for temporary credentials.
   */
  sessionToken?: string;
  /**
   * A credentials object or a provider that resolves (and refreshes)
   * credentials. Resolved on every {@link AwsClient.sign} / {@link
   * AwsClient.fetch} call, so temporary credentials stay valid across retries.
   */
  credentials?: AwsCredentials | AwsCredentialProvider;
  /**
   * The AWS service name used in the signature. If omitted, it is derived from
   * the request hostname.
   */
  service?: string;
  /**
   * The AWS region used in the signature. If omitted, it is derived from the
   * request hostname (falling back to `us-east-1`).
   */
  region?: string;
  /**
   * A cache of derived HMAC signing keys. One is created if not provided.
   */
  cache?: Map<string, ArrayBuffer>;
  /**
   * Number of times {@link AwsClient.fetch} retries on 5xx/429 responses.
   */
  retries?: number;
  /**
   * Base retry delay in milliseconds for {@link AwsClient.fetch}.
   */
  initRetryMs?: number;
}

/**
 * Resolves {@link AwsCredentials} on demand. Providers are expected to cache
 * internally and refresh before expiry, so callers may invoke them on every
 * request (including once per retry attempt) cheaply.
 *
 * @beta
 */
export declare type AwsCredentialProvider = () => Promise<AwsCredentials>;

/**
 * A set of AWS credentials used to sign requests with AWS Signature Version 4.
 *
 * For static IAM user keys, only `accessKeyId` and `secretAccessKey` are set.
 * For temporary credentials obtained from STS (`AssumeRole`,
 * `AssumeRoleWithWebIdentity`), `sessionToken` and `expiration` are also
 * populated.
 *
 * @beta
 */
export declare interface AwsCredentials {
  /**
   * The AWS access key ID.
   */
  accessKeyId: string;
  /**
   * The AWS secret access key.
   */
  secretAccessKey: string;
  /**
   * The AWS session token. Present for temporary credentials.
   */
  sessionToken?: string;
  /**
   * The moment the credentials expire. Present for temporary credentials and
   * used to drive cache refresh. Static credentials have no expiration.
   */
  expiration?: Date;
}

/**
 * Request initializer accepted by {@link AwsClient.sign} and
 * {@link AwsClient.fetch}. Compatible with aws4fetch's `AwsRequestInit`.
 *
 * @beta
 */
export declare interface AwsRequestInit extends Omit<RequestInit, "body"> {
  body?: ArrayBuffer | string | null;
  aws?: {
    accessKeyId?: string;
    secretAccessKey?: string;
    sessionToken?: string;
    service?: string;
    region?: string;
    cache?: Map<string, ArrayBuffer>;
    datetime?: string;
    signQuery?: boolean;
    appendSessionToken?: boolean;
    allHeaders?: boolean;
    singleEncode?: boolean;
  };
}

/**
 * A low-level AWS Signature Version 4 signer. API-compatible with aws4fetch's
 * `AwsV4Signer`. Most callers should use {@link AwsClient} or
 * {@link signRequest} instead.
 *
 * @beta
 */
export declare class AwsV4Signer {
  private method;
  private url;
  private headers;
  private body?;
  private accessKeyId;
  private secretAccessKey;
  private sessionToken?;
  private service;
  private region;
  private cache;
  private datetime;
  private signQuery?;
  private appendSessionToken?;
  private signableHeaders;
  private signedHeaders;
  private canonicalHeaders;
  private credentialString;
  private encodedPath;
  private encodedSearch;
  constructor({
    method,
    url,
    headers,
    body,
    accessKeyId,
    secretAccessKey,
    sessionToken,
    service,
    region,
    cache,
    datetime,
    signQuery,
    appendSessionToken,
    allHeaders,
    singleEncode,
  }: {
    method?: string;
    url: string;
    headers?: HeadersInit;
    body?: BodyInit | null;
    accessKeyId: string;
    secretAccessKey: string;
    sessionToken?: string;
    service?: string;
    region?: string;
    cache?: Map<string, ArrayBuffer>;
    datetime?: string;
    signQuery?: boolean;
    appendSessionToken?: boolean;
    allHeaders?: boolean;
    singleEncode?: boolean;
  });
  sign(): Promise<{
    method: string;
    url: URL;
    headers: Headers;
    body?: BodyInit | null;
  }>;
  authHeader(): Promise<string>;
  signature(): Promise<string>;
  stringToSign(): Promise<string>;
  canonicalString(): Promise<string>;
  hexBodyHash(): Promise<string>;
}

/**
 * Base logger interface with methods for each log level.
 * @beta
 */
declare interface BaseLogger {
  debug(...messages: unknown[]): void;
  info(...messages: unknown[]): void;
  log(...messages: unknown[]): void;
  warn(...messages: unknown[]): void;
  error(...messages: unknown[]): void;
}

/**
 * @public
 */
declare interface BuildRouteConfiguration {
  path: string;
  methods: HttpMethod[];
  /**
   * @deprecated This property is not used and will be removed in future versions
   */
  label?: string;
  /**
   * @deprecated This property is not used and will be removed in future versions
   */
  key?: string;
  handler: HandlerDefinition;
  corsPolicy?: CorsPolicy;
  /**
   * @deprecated This property is deprecated. Use route.raw() instead.
   */
  custom?: any;
  mcp?: {
    enabled?: boolean;
  };
  policies?: {
    inbound?: string[];
    outbound?: string[];
  };
  /**
   * @deprecated This property is not used and will be removed in future versions
   */
  excludeFromOpenApi?: boolean;
  pathPattern?: string;
  /**
   * Build-time metadata for this route.
   */
  metadata?: {
    /**
     * The source file this route was generated from.
     */
    filepath: string;
  };
  /* Excluded from this release type: raw */
}

/**
 * The 2-letter continent codes Cloudflare uses
 * @public
 */
declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA";

/**
 * @public
 */
declare type CorsPolicy = string | "anything-goes" | "none";

declare const EventType: {
  readonly AI_GATEWAY_COST_SUM: "ai_gateway_cost_sum";
  readonly AI_GATEWAY_REQUEST_COUNT: "ai_gateway_request_count";
  readonly AI_GATEWAY_TOKEN_SUM: "ai_gateway_token_sum";
  readonly AI_GATEWAY_LATENCY_HISTOGRAM: "ai_gateway_latency_histogram";
  readonly AI_GATEWAY_WARNING_COUNT: "ai_gateway_warning_count";
  readonly AI_GATEWAY_BLOCKED_COUNT: "ai_gateway_blocked_count";
  readonly AI_GATEWAY_FALLBACK_COUNT: "ai_gateway_fallback_count";
  readonly MCP_REQUEST_RECEIVED: "mcp_request_received";
  readonly MCP_REQUEST_COMPLETED: "mcp_request_completed";
  readonly MCP_REQUEST_REJECTED: "mcp_request_rejected";
  readonly MCP_INITIALIZE_NEGOTIATED: "mcp_initialize_negotiated";
  readonly MCP_CLIENT_UNSUPPORTED_BEHAVIOR: "mcp_client_unsupported_behavior";
  readonly MCP_CAPABILITY_LISTED: "mcp_capability_listed";
  readonly MCP_CAPABILITY_INVOKED: "mcp_capability_invoked";
  readonly MCP_CAPABILITY_COMPLETED: "mcp_capability_completed";
  readonly MCP_CAPABILITY_FAILED: "mcp_capability_failed";
  readonly MCP_CAPABILITY_CONNECT_REQUIRED: "mcp_capability_connect_required";
  readonly MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED: "mcp_auth_downstream_token_validated";
  readonly MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED: "mcp_auth_downstream_token_rejected";
  readonly MCP_OAUTH_CLIENT_REGISTERED: "mcp_oauth_client_registered";
  readonly MCP_OAUTH_AUTHORIZE_STARTED: "mcp_oauth_authorize_started";
  readonly MCP_OAUTH_AUTHORIZE_AWAITING_SETUP: "mcp_oauth_authorize_awaiting_setup";
  readonly MCP_OAUTH_TOKEN_ISSUED: "mcp_oauth_token_issued";
  readonly MCP_OAUTH_TOKEN_REFRESH_ROTATED: "mcp_oauth_token_refresh_rotated";
  readonly MCP_OAUTH_TOKEN_REVOKED: "mcp_oauth_token_revoked";
  readonly MCP_AUTH_UPSTREAM_CONNECT_REQUIRED: "mcp_auth_upstream_connect_required";
  readonly MCP_AUTH_UPSTREAM_CONNECT_STARTED: "mcp_auth_upstream_connect_started";
  readonly MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED: "mcp_auth_upstream_callback_received";
  readonly MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED: "mcp_auth_upstream_token_exchange_succeeded";
  readonly MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED: "mcp_auth_upstream_token_exchange_failed";
  readonly MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED: "mcp_auth_upstream_credential_resolved";
  readonly MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING: "mcp_auth_upstream_credential_missing";
  readonly MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED: "mcp_auth_upstream_reconsent_required";
  readonly GRAPHQL_OPERATION: "graphql_operation";
  readonly CACHE_OPERATION: "cache_operation";
  readonly HANDLER_EXECUTION: "handler_execution";
};

declare type EventType = (typeof EventType)[keyof typeof EventType];

/**
 * Creates a provider that assumes an IAM role via STS `AssumeRole`, signing the
 * call with the supplied master credentials. Resolved credentials are cached
 * in memory and refreshed before expiry.
 *
 * Name mirrors `@aws-sdk/credential-providers`.
 *
 * @beta
 */
export declare function fromTemporaryCredentials(
  options: FromTemporaryCredentialsOptions
): AwsCredentialProvider;

/**
 * Options for {@link fromTemporaryCredentials}.
 * @beta
 */
export declare interface FromTemporaryCredentialsOptions {
  /** The AWS region for the STS endpoint and signature. */
  region: string;
  /** The ARN of the IAM role to assume. */
  roleArn: string;
  /** The STS role session name. Default "zuplo-gateway". */
  roleSessionName?: string;
  /** The lifetime of the temporary credentials in seconds (900-43200). */
  durationSeconds?: number;
  /** The external ID, when the role's trust policy requires one. */
  externalId?: string;
  /** Credentials used to sign the `AssumeRole` call itself. */
  masterCredentials: AwsCredentials | AwsCredentialProvider;
  /** Overrides the STS endpoint (GovCloud/China partitions). */
  stsEndpoint?: string;
  /** Seconds before expiry that cached credentials are refreshed. Default 300. */
  expirationOffsetSeconds?: number;
  /** Retry configuration for the STS call. */
  retry?: TokenRetryOptions;
  /** Optional logger for STS failures. */
  logger?: BaseLogger;
}

/**
 * Creates a provider that assumes an IAM role via STS
 * `AssumeRoleWithWebIdentity` using an OIDC web identity token. No AWS
 * credentials are required to make the (unsigned) call.
 *
 * Name mirrors `@aws-sdk/credential-providers`.
 *
 * @beta
 */
export declare function fromWebToken(
  options: FromWebTokenOptions
): AwsCredentialProvider;

/**
 * Options for {@link fromWebToken}.
 * @beta
 */
export declare interface FromWebTokenOptions {
  /** The AWS region for the STS endpoint. */
  region: string;
  /** The IAM role to assume. */
  roleArn: string;
  /** The OIDC web identity token, or a supplier invoked on each (re)issue. */
  webIdentityToken: string | (() => Promise<string>);
  /** The STS role session name. Default "zuplo-gateway". */
  roleSessionName?: string;
  /** The lifetime of the temporary credentials in seconds (900-43200). */
  durationSeconds?: number;
  /** Overrides the STS endpoint (GovCloud/China partitions). */
  stsEndpoint?: string;
  /** Seconds before expiry that cached credentials are refreshed. Default 300. */
  expirationOffsetSeconds?: number;
  /** Retry configuration for the STS call. */
  retry?: TokenRetryOptions;
  /** Optional logger for STS failures. */
  logger?: BaseLogger;
}

/**
 * Creates a provider that assumes an IAM role via STS
 * `AssumeRoleWithWebIdentity`, using Zuplo's ambient OIDC identity
 * ({@link ZuploServices.getIDToken}) as the web identity token. This is the
 * fully keyless (secretless) path.
 *
 * @beta
 */
export declare function fromZuploIdentity(
  options: FromZuploIdentityOptions
): AwsCredentialProvider;

/**
 * Options for {@link fromZuploIdentity}.
 * @beta
 */
export declare interface FromZuploIdentityOptions {
  /** The AWS region for the STS endpoint. */
  region: string;
  /** The IAM role to assume. Its trust policy must trust the Zuplo OIDC IdP. */
  roleArn: string;
  /** The current ZuploContext (used to mint the ambient OIDC token). */
  context: ZuploContext;
  /**
   * The audience (`aud` claim) of the Zuplo-issued OIDC token. Must match a
   * client ID configured on the IAM OIDC identity provider. Default
   * "sts.amazonaws.com".
   */
  audience?: string;
  /** The STS role session name. Default "zuplo-gateway". */
  roleSessionName?: string;
  /** The lifetime of the temporary credentials in seconds (900-43200). */
  durationSeconds?: number;
  /** Overrides the STS endpoint (GovCloud/China partitions). */
  stsEndpoint?: string;
  /** Seconds before expiry that cached credentials are refreshed. Default 300. */
  expirationOffsetSeconds?: number;
  /** Retry configuration for the STS call. */
  retry?: TokenRetryOptions;
  /** Optional logger for STS failures. */
  logger?: BaseLogger;
}

/**
 * Reads the AWS credential provider registered on the request context by an
 * upstream AWS auth policy, or `undefined` if none has been registered.
 *
 * @beta
 * @param context - The current ZuploContext
 * @returns The registered credential provider, or `undefined`
 */
export declare function getAwsCredentialProvider(
  context: ZuploContext
): AwsCredentialProvider | undefined;

/**
 * @public
 */
declare interface HandlerDefinition {
  module: any;
  export: string;
  options?: unknown;
}

/**
 * @public
 */
declare type HttpMethod =
  | "GET"
  | "HEAD"
  | "POST"
  | "PUT"
  | "DELETE"
  | "CONNECT"
  | "OPTIONS"
  | "TRACE"
  | "PATCH";

/**
 * @beta
 */
declare enum HttpStatusCode {
  /**
   * The server has received the request headers and the client should proceed to send the request body
   * (in the case of a request for which a body needs to be sent; for example, a POST request).
   * Sending a large request body to a server after a request has been rejected for inappropriate headers would be inefficient.
   * To have a server check the request's headers, a client must send Expect: 100-continue as a header in its initial request
   * and receive a 100 Continue status code in response before sending the body. The response 417 Expectation Failed indicates the request should not be continued.
   */
  CONTINUE = 100,
  /**
   * The requester has asked the server to switch protocols and the server has agreed to do so.
   */
  SWITCHING_PROTOCOLS = 101,
  /**
   * A WebDAV request may contain many sub-requests involving file operations, requiring a long time to complete the request.
   * This code indicates that the server has received and is processing the request, but no response is available yet.
   * This prevents the client from timing out and assuming the request was lost.
   * @deprecated This status code is deprecated and shouldn't be sent any more. Clients may still accept it, but simply ignore them.
   */
  PROCESSING = 102,
  /**
   * This response may be sent by a server while it is still preparing a
   * response, with hints about the resources that the server is expecting
   * the final response will link. This allows a browser to start preloading
   * resources even before the server has prepared and sent that final response.
   */
  EARLY_HINTS = 103,
  /**
   * Standard response for successful HTTP requests.
   * The actual response will depend on the request method used.
   * In a GET request, the response will contain an entity corresponding to the requested resource.
   * In a POST request, the response will contain an entity describing or containing the result of the action.
   */
  OK = 200,
  /**
   * The request has been fulfilled, resulting in the creation of a new resource.
   */
  CREATED = 201,
  /**
   * The request has been accepted for processing, but the processing has not been completed.
   * The request might or might not be eventually acted upon, and may be disallowed when processing occurs.
   */
  ACCEPTED = 202,
  /**
   * SINCE HTTP/1.1
   * The server is a transforming proxy that received a 200 OK from its origin,
   * but is returning a modified version of the origin's response.
   */
  NON_AUTHORITATIVE_INFORMATION = 203,
  /**
   * The server successfully processed the request and is not returning any content.
   */
  NO_CONTENT = 204,
  /**
   * The server successfully processed the request, but is not returning any content.
   * Unlike a 204 response, this response requires that the requester reset the document view.
   */
  RESET_CONTENT = 205,
  /**
   * The server is delivering only part of the resource (byte serving) due to a range header sent by the client.
   * The range header is used by HTTP clients to enable resuming of interrupted downloads,
   * or split a download into multiple simultaneous streams.
   */
  PARTIAL_CONTENT = 206,
  /**
   * The message body that follows is an XML message and can contain a number of separate response codes,
   * depending on how many sub-requests were made.
   */
  MULTI_STATUS = 207,
  /**
   * The members of a DAV binding have already been enumerated in a preceding part of the (multistatus) response,
   * and are not being included again.
   */
  ALREADY_REPORTED = 208,
  /**
   * The server has fulfilled a request for the resource,
   * and the response is a representation of the result of one or more instance-manipulations applied to the current instance.
   */
  IM_USED = 226,
  /**
   * Indicates multiple options for the resource from which the client may choose (via agent-driven content negotiation).
   * For example, this code could be used to present multiple video format options,
   * to list files with different filename extensions, or to suggest word-sense disambiguation.
   */
  MULTIPLE_CHOICES = 300,
  /**
   * This and all future requests should be directed to the given URI.
   */
  MOVED_PERMANENTLY = 301,
  /**
   * This is an example of industry practice contradicting the standard.
   * The HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect
   * (the original describing phrase was "Moved Temporarily"), but popular browsers implemented 302
   * with the functionality of a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307
   * to distinguish between the two behaviours. However, some Web applications and frameworks
   * use the 302 status code as if it were the 303.
   */
  FOUND = 302,
  /**
   * SINCE HTTP/1.1
   * The response to the request can be found under another URI using a GET method.
   * When received in response to a POST (or PUT/DELETE), the client should presume that
   * the server has received the data and should issue a redirect with a separate GET message.
   */
  SEE_OTHER = 303,
  /**
   * Indicates that the resource has not been modified since the version specified by the request headers If-Modified-Since or If-None-Match.
   * In such case, there is no need to retransmit the resource since the client still has a previously-downloaded copy.
   */
  NOT_MODIFIED = 304,
  /**
   * SINCE HTTP/1.1
   * The requested resource is available only through a proxy, the address for which is provided in the response.
   * Many HTTP clients (such as Mozilla and Internet Explorer) do not correctly handle responses with this status code, primarily for security reasons.
   */
  USE_PROXY = 305,
  /**
   * No longer used. Originally meant "Subsequent requests should use the specified proxy."
   * @deprecated No longer used
   */
  SWITCH_PROXY = 306,
  /**
   * SINCE HTTP/1.1
   * In this case, the request should be repeated with another URI; however, future requests should still use the original URI.
   * In contrast to how 302 was historically implemented, the request method is not allowed to be changed when reissuing the original request.
   * For example, a POST request should be repeated using another POST request.
   */
  TEMPORARY_REDIRECT = 307,
  /**
   * The request and all future requests should be repeated using another URI.
   * 307 and 308 parallel the behaviors of 302 and 301, but do not allow the HTTP method to change.
   * So, for example, submitting a form to a permanently redirected resource may continue smoothly.
   */
  PERMANENT_REDIRECT = 308,
  /**
   * The server cannot or will not process the request due to an apparent client error
   * (e.g., malformed request syntax, too large size, invalid request message framing, or deceptive request routing).
   */
  BAD_REQUEST = 400,
  /**
   * Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet
   * been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the
   * requested resource. See Basic access authentication and Digest access authentication. 401 semantically means
   * "unauthenticated",i.e. the user does not have the necessary credentials.
   */
  UNAUTHORIZED = 401,
  /**
   * Reserved for future use. The original intention was that this code might be used as part of some form of digital
   * cash or micro payment scheme, but that has not happened, and this code is not usually used.
   * Google Developers API uses this status if a particular developer has exceeded the daily limit on requests.
   */
  PAYMENT_REQUIRED = 402,
  /**
   * The request was valid, but the server is refusing action.
   * The user might not have the necessary permissions for a resource.
   */
  FORBIDDEN = 403,
  /**
   * The requested resource could not be found but may be available in the future.
   * Subsequent requests by the client are permissible.
   */
  NOT_FOUND = 404,
  /**
   * A request method is not supported for the requested resource;
   * for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource.
   */
  METHOD_NOT_ALLOWED = 405,
  /**
   * The requested resource is capable of generating only content not acceptable according to the Accept headers sent in the request.
   */
  NOT_ACCEPTABLE = 406,
  /**
   * The client must first authenticate itself with the proxy.
   */
  PROXY_AUTHENTICATION_REQUIRED = 407,
  /**
   * The server timed out waiting for the request.
   * According to HTTP specifications:
   * "The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time."
   */
  REQUEST_TIMEOUT = 408,
  /**
   * Indicates that the request could not be processed because of conflict in the request,
   * such as an edit conflict between multiple simultaneous updates.
   */
  CONFLICT = 409,
  /**
   * Indicates that the resource requested is no longer available and will not be available again.
   * This should be used when a resource has been intentionally removed and the resource should be purged.
   * Upon receiving a 410 status code, the client should not request the resource in the future.
   * Clients such as search engines should remove the resource from their indices.
   * Most use cases do not require clients and search engines to purge the resource, and a "404 Not Found" may be used instead.
   */
  GONE = 410,
  /**
   * The request did not specify the length of its content, which is required by the requested resource.
   */
  LENGTH_REQUIRED = 411,
  /**
   * The server does not meet one of the preconditions that the requester put on the request.
   */
  PRECONDITION_FAILED = 412,
  /**
   * The request is larger than the server is willing or able to process. Previously called "Request Entity Too Large".
   */
  CONTENT_TOO_LARGE = 413,
  /* Excluded from this release type: PAYLOAD_TOO_LARGE */
  /**
   * The URI provided was too long for the server to process. Often the result of too much data being encoded as a query-string of a GET request,
   * in which case it should be converted to a POST request.
   * Called "Request-URI Too Long" previously.
   */
  URI_TOO_LONG = 414,
  /**
   * The request entity has a media type which the server or resource does not support.
   * For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.
   */
  UNSUPPORTED_MEDIA_TYPE = 415,
  /**
   * The client has asked for a portion of the file (byte serving), but the server cannot supply that portion.
   * For example, if the client asked for a part of the file that lies beyond the end of the file.
   * Called "Requested Range Not Satisfiable" previously.
   */
  RANGE_NOT_SATISFIABLE = 416,
  /**
   * The server cannot meet the requirements of the Expect request-header field.
   */
  EXPECTATION_FAILED = 417,
  /**
   * This code was defined in 1998 as one of the traditional IETF April Fools' jokes, in RFC 2324, Hyper Text Coffee Pot Control Protocol,
   * and is not expected to be implemented by actual HTTP servers. The RFC specifies this code should be returned by
   * teapots requested to brew coffee. This HTTP status is used as an Easter egg in some websites, including Google.com.
   */
  I_AM_A_TEAPOT = 418,
  /**
   * The request was directed at a server that is not able to produce a response (for example because a connection reuse).
   */
  MISDIRECTED_REQUEST = 421,
  /* Excluded from this release type: UNPROCESSABLE_ENTITY */
  /**
   * The request was well-formed but was unable to be followed due to semantic errors.
   */
  UNPROCESSABLE_CONTENT = 422,
  /**
   * The resource that is being accessed is locked.
   */
  LOCKED = 423,
  /**
   * The request failed due to failure of a previous request (e.g., a PROPPATCH).
   */
  FAILED_DEPENDENCY = 424,
  /**
   * The server is unwilling to risk processing a request that might be
   * replayed, which creates the potential for a replay attack.
   */
  TOO_EARLY = 425,
  /**
   * The client should switch to a different protocol such as TLS/1.0, given in the Upgrade header field.
   */
  UPGRADE_REQUIRED = 426,
  /**
   * The origin server requires the request to be conditional.
   * Intended to prevent "the 'lost update' problem, where a client
   * GETs a resource's state, modifies it, and PUTs it back to the server,
   * when meanwhile a third party has modified the state on the server, leading to a conflict."
   */
  PRECONDITION_REQUIRED = 428,
  /**
   * The user has sent too many requests in a given amount of time. Intended for use with rate-limiting schemes.
   */
  TOO_MANY_REQUESTS = 429,
  /**
   * The server is unwilling to process the request because either an individual header field,
   * or all the header fields collectively, are too large.
   */
  REQUEST_HEADER_FIELDS_TOO_LARGE = 431,
  /**
   * A server operator has received a legal demand to deny access to a resource or to a set of resources
   * that includes the requested resource. The code 451 was chosen as a reference to the novel Fahrenheit 451.
   */
  UNAVAILABLE_FOR_LEGAL_REASONS = 451,
  /**
   * A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.
   */
  INTERNAL_SERVER_ERROR = 500,
  /**
   * The server either does not recognize the request method, or it lacks the ability to fulfill the request.
   * Usually this implies future availability (e.g., a new feature of a web-service API).
   */
  NOT_IMPLEMENTED = 501,
  /**
   * The server was acting as a gateway or proxy and received an invalid response from the upstream server.
   */
  BAD_GATEWAY = 502,
  /**
   * The server is currently unavailable (because it is overloaded or down for maintenance).
   * Generally, this is a temporary state.
   */
  SERVICE_UNAVAILABLE = 503,
  /**
   * The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.
   */
  GATEWAY_TIMEOUT = 504,
  /**
   * The server does not support the HTTP protocol version used in the request
   */
  HTTP_VERSION_NOT_SUPPORTED = 505,
  /**
   * Transparent content negotiation for the request results in a circular reference.
   */
  VARIANT_ALSO_NEGOTIATES = 506,
  /**
   * The server is unable to store the representation needed to complete the request.
   */
  INSUFFICIENT_STORAGE = 507,
  /**
   * The server detected an infinite loop while processing the request.
   */
  LOOP_DETECTED = 508,
  /**
   * Further extensions to the request are required for the server to fulfill it.
   */
  NOT_EXTENDED = 510,
  /**
   * The client needs to authenticate to gain network access.
   * Intended for use by intercepting proxies used to control access to the network (e.g., "captive portals" used
   * to require agreement to Terms of Service before granting full Internet access via a Wi-Fi hotspot).
   */
  NETWORK_AUTHENTICATION_REQUIRED = 511,
}

declare type HttpStatusCodeRangeDefinition =
  | "1XX"
  | "2XX"
  | "3XX"
  | "4XX"
  | "5XX";

/**
 * @public
 */
declare interface IncomingRequestProperties {
  /**
   * The IP address of the client that made the incoming request, for example,
   * "203.0.113.7".
   *
   * Use this rather than reading an IP header off `request` yourself. Which
   * header carries the address differs by deployment, and some are removed
   * from the request before your code runs, so reading one directly is either
   * empty or wrong depending on where the gateway is running.
   *
   * The value is `undefined` when the caller could not be identified, so
   * handle that case rather than substituting a placeholder, which would
   * become one shared identity for every unidentified caller. During local
   * development, where nothing identifies the caller, it falls back to
   * `"127.0.0.1"` instead.
   *
   * If your own CDN or load balancer sits in front of Zuplo, this is the
   * address of that hop rather than the end user's.
   *
   * @see {@link https://zuplo.com/docs/articles/check-ip-address} for when
   * this address can be trusted on each deployment type.
   *
   * @example
   * ```ts
   * export default async function (request: ZuploRequest, context: ZuploContext) {
   *   const ip = context.incomingRequestProperties.ip;
   *   return new Response(ip ?? "unknown");
   * }
   * ```
   */
  readonly ip: string | undefined;
  /**
   * ASN of the incoming request, for example, 395747.
   */
  readonly asn: number | undefined;
  /**
   * The organization which owns the ASN of the incoming request,
   * for example, Google Cloud.
   */
  readonly asOrganization: string | undefined;
  /**
   * City of the incoming request, for example, "Austin".
   */
  readonly city: string | undefined;
  /**
   * Continent of the incoming request, for example, "NA".
   */
  readonly continent: ContinentCode | undefined;
  /**
   * The two-letter country code in the request.
   * @see {@link https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2|ISO 3166-1 alpha-2}
   */
  readonly country: Iso3166Alpha2Code | undefined;
  /**
   * Latitude of the incoming request, for example, "30.27130".
   */
  readonly latitude: string | undefined;
  /**
   * Longitude of the incoming request, for example, "-97.74260".
   */
  readonly longitude: string | undefined;
  /**
   * The three-letter IATA airport code of the data center that the request hit,
   * for example, "DFW".
   * @see {@link https://en.wikipedia.org/wiki/IATA_airport_code|IATA airport code}
   */
  readonly colo: string | undefined;
  /**
   * Postal code of the incoming request, for example, "78701".
   */
  readonly postalCode: string | undefined;
  /**
   * Metro code (DMA) of the incoming request, for example, "635".
   */
  readonly metroCode: string | undefined;
  /**
   * If known, the ISO 3166-2 name for the first level region associated with
   * the IP address of the incoming request, for example, "Texas".
   * @see {@link https://en.wikipedia.org/wiki/ISO_3166-2|ISO 3166-2}
   */
  readonly region: string | undefined;
  /**
   * If known, the ISO 3166-2 code for the first-level region associated with
   * the IP address of the incoming request, for example, "TX".
   * @see {@link https://en.wikipedia.org/wiki/ISO_3166-2|ISO 3166-2}
   */
  readonly regionCode: string | undefined;
  /**
   * Timezone of the incoming request, for example, "America/Chicago".
   */
  readonly timezone: string | undefined;
  /**
   * If available, the HTTP protocol of the incoming request, for example, "HTTP/1.1".
   */
  readonly httpProtocol: string | undefined;
  /* Excluded from this release type: clientCert */
  /* Excluded from this release type: clientMtlsVerificationStatus */
  /* Excluded from this release type: clientMtlsVerificationReason */
  /* Excluded from this release type: clientCertFingerprintSha256 */
  /* Excluded from this release type: clientCertNotBefore */
  /* Excluded from this release type: clientCertNotAfter */
  /* Excluded from this release type: clientCertIssuerDn */
  /* Excluded from this release type: clientCertSubjectDn */
}

/**
 * ISO 3166-1 Alpha-2 codes
 * @public
 */
declare type Iso3166Alpha2Code =
  | "AD"
  | "AE"
  | "AF"
  | "AG"
  | "AI"
  | "AL"
  | "AM"
  | "AO"
  | "AQ"
  | "AR"
  | "AS"
  | "AT"
  | "AU"
  | "AW"
  | "AX"
  | "AZ"
  | "BA"
  | "BB"
  | "BD"
  | "BE"
  | "BF"
  | "BG"
  | "BH"
  | "BI"
  | "BJ"
  | "BL"
  | "BM"
  | "BN"
  | "BO"
  | "BQ"
  | "BR"
  | "BS"
  | "BT"
  | "BV"
  | "BW"
  | "BY"
  | "BZ"
  | "CA"
  | "CC"
  | "CD"
  | "CF"
  | "CG"
  | "CH"
  | "CI"
  | "CK"
  | "CL"
  | "CM"
  | "CN"
  | "CO"
  | "CR"
  | "CU"
  | "CV"
  | "CW"
  | "CX"
  | "CY"
  | "CZ"
  | "DE"
  | "DJ"
  | "DK"
  | "DM"
  | "DO"
  | "DZ"
  | "EC"
  | "EE"
  | "EG"
  | "EH"
  | "ER"
  | "ES"
  | "ET"
  | "FI"
  | "FJ"
  | "FK"
  | "FM"
  | "FO"
  | "FR"
  | "GA"
  | "GB"
  | "GD"
  | "GE"
  | "GF"
  | "GG"
  | "GH"
  | "GI"
  | "GL"
  | "GM"
  | "GN"
  | "GP"
  | "GQ"
  | "GR"
  | "GS"
  | "GT"
  | "GU"
  | "GW"
  | "GY"
  | "HK"
  | "HM"
  | "HN"
  | "HR"
  | "HT"
  | "HU"
  | "ID"
  | "IE"
  | "IL"
  | "IM"
  | "IN"
  | "IO"
  | "IQ"
  | "IR"
  | "IS"
  | "IT"
  | "JE"
  | "JM"
  | "JO"
  | "JP"
  | "KE"
  | "KG"
  | "KH"
  | "KI"
  | "KM"
  | "KN"
  | "KP"
  | "KR"
  | "KW"
  | "KY"
  | "KZ"
  | "LA"
  | "LB"
  | "LC"
  | "LI"
  | "LK"
  | "LR"
  | "LS"
  | "LT"
  | "LU"
  | "LV"
  | "LY"
  | "MA"
  | "MC"
  | "MD"
  | "ME"
  | "MF"
  | "MG"
  | "MH"
  | "MK"
  | "ML"
  | "MM"
  | "MN"
  | "MO"
  | "MP"
  | "MQ"
  | "MR"
  | "MS"
  | "MT"
  | "MU"
  | "MV"
  | "MW"
  | "MX"
  | "MY"
  | "MZ"
  | "NA"
  | "NC"
  | "NE"
  | "NF"
  | "NG"
  | "NI"
  | "NL"
  | "NO"
  | "NP"
  | "NR"
  | "NU"
  | "NZ"
  | "OM"
  | "PA"
  | "PE"
  | "PF"
  | "PG"
  | "PH"
  | "PK"
  | "PL"
  | "PM"
  | "PN"
  | "PR"
  | "PS"
  | "PT"
  | "PW"
  | "PY"
  | "QA"
  | "RE"
  | "RO"
  | "RS"
  | "RU"
  | "RW"
  | "SA"
  | "SB"
  | "SC"
  | "SD"
  | "SE"
  | "SG"
  | "SH"
  | "SI"
  | "SJ"
  | "SK"
  | "SL"
  | "SM"
  | "SN"
  | "SO"
  | "SR"
  | "SS"
  | "ST"
  | "SV"
  | "SX"
  | "SY"
  | "SZ"
  | "TC"
  | "TD"
  | "TF"
  | "TG"
  | "TH"
  | "TJ"
  | "TK"
  | "TL"
  | "TM"
  | "TN"
  | "TO"
  | "TR"
  | "TT"
  | "TV"
  | "TW"
  | "TZ"
  | "UA"
  | "UG"
  | "UM"
  | "US"
  | "UY"
  | "UZ"
  | "VA"
  | "VC"
  | "VE"
  | "VG"
  | "VI"
  | "VN"
  | "VU"
  | "WF"
  | "WS"
  | "YE"
  | "YT"
  | "ZA"
  | "ZM"
  | "ZW";

declare type JsonArray = JsonValue[] | readonly JsonValue[];

/**
 Matches a JSON object.
 This type can be useful to enforce some input to be JSON-compatible or as a super-type to be extended from. Don't use this as a direct return type as the user would have to double-cast it: `jsonObject as unknown as CustomResponse`. Instead, you could extend your CustomResponse type from it to ensure your type only uses JSON-compatible types: `interface CustomResponse extends JsonObject { … }`.
 */
declare type JsonObject = {
  [Key in string]: JsonValue;
} & {
  [Key in string]?: JsonValue | undefined;
};

declare type JsonPrimitive = string | number | boolean | null;

/**
 Matches any valid JSON value.
 @see `Jsonify` if you need to transform a type to one that is assignable to `JsonValue`.
 */
declare type JsonValue = JsonPrimitive | JsonObject | JsonArray;

/**
 * Logger to be used in the runtime via context.log.
 * You can set per-request properties that will be included in all log entries for this request.
 * @beta
 */
declare interface Logger extends BaseLogger {
  /**
   * Set properties for this request. They are added to every later log entry
   * for this request that a log plugin ships (Datadog, Splunk, Loki and the
   * others), and to the request's row in Zuplo's request log, which the log
   * viewer in the Zuplo Portal shows in the request's details.
   *
   * Properties apply only to the current request. Each call merges into the
   * properties already set, and a later value for the same key overwrites an
   * earlier one. In log entries, a per-request property takes precedence over
   * a static field with the same name configured in the logging plugin. A
   * request made with `context.invokeRoute` has its own properties and its
   * own row.
   *
   * To keep request rows small, a row holds at most 64 properties, a key can
   * be at most 128 characters, and a value at most 2048 characters. A longer
   * value is truncated on the row, and a property over the other limits is
   * left off the row. Log entries are not limited this way.
   *
   * @param properties - Key-value pairs for this request. Values must be string, number, or boolean.
   *
   * @example
   * ```ts
   * export default async function (request: ZuploRequest, context: ZuploContext) {
   *   // Set properties that will be included in all logs for this request
   *   context.log.setLogProperties({ http_status_code: 400, user_id: "123" });
   *
   *   context.log.error("Request failed"); // Will include http_status_code and user_id
   *
   *   return new Response("Error", { status: 400 });
   * }
   * ```
   */
  setLogProperties?(
    properties: Record<string, string | number | boolean>
  ): void;
}

declare type Modify<T, R> = Omit<T, keyof R> & R;

/**
 * @public
 */
declare interface OnResponseSendingFinalHook {
  (
    response: Response,
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<void> | void;
}

/**
 * @public
 */
declare interface OnResponseSendingHook {
  (
    response: Response,
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<Response> | Response;
}

declare namespace OpenAPIV3 {
  interface Document<T extends {} = {}> {
    openapi: string;
    info: InfoObject;
    servers?: ServerObject[];
    paths: PathsObject<T>;
    components?: ComponentsObject;
    security?: SecurityRequirementObject[];
    tags?: TagObject[];
    externalDocs?: ExternalDocumentationObject;
    "x-express-openapi-additional-middleware"?: (
      | ((request: any, response: any, next: any) => Promise<void>)
      | ((request: any, response: any, next: any) => void)
    )[];
    "x-express-openapi-validation-strict"?: boolean;
  }
  interface InfoObject {
    title: string;
    description?: string;
    termsOfService?: string;
    contact?: ContactObject;
    license?: LicenseObject;
    version: string;
  }
  interface ContactObject {
    name?: string;
    url?: string;
    email?: string;
  }
  interface LicenseObject {
    name: string;
    url?: string;
  }
  interface ServerObject {
    url: string;
    description?: string;
    variables?: {
      [variable: string]: ServerVariableObject;
    };
  }
  interface ServerVariableObject {
    enum?: string[];
    default: string;
    description?: string;
  }
  interface PathsObject<T extends {} = {}, P extends {} = {}> {
    [pattern: string]: (PathItemObject<T> & P) | undefined;
  }
  enum HttpMethods {
    GET = "get",
    PUT = "put",
    POST = "post",
    DELETE = "delete",
    OPTIONS = "options",
    HEAD = "head",
    PATCH = "patch",
    TRACE = "trace",
  }
  type PathItemObject<T extends {} = {}> = {
    $ref?: string;
    summary?: string;
    description?: string;
    servers?: ServerObject[];
    parameters?: (ReferenceObject | ParameterObject)[];
  } & {
    [method in HttpMethods]?: OperationObject<T>;
  };
  type OperationObject<T extends {} = {}> = {
    tags?: string[];
    summary?: string;
    description?: string;
    externalDocs?: ExternalDocumentationObject;
    operationId?: string;
    parameters?: (ReferenceObject | ParameterObject)[];
    requestBody?: ReferenceObject | RequestBodyObject;
    responses: ResponsesObject;
    callbacks?: {
      [callback: string]: ReferenceObject | CallbackObject;
    };
    deprecated?: boolean;
    security?: SecurityRequirementObject[];
    servers?: ServerObject[];
  } & T;
  interface ExternalDocumentationObject {
    description?: string;
    url: string;
  }
  interface ParameterObject extends ParameterBaseObject {
    name: string;
    in: string;
  }
  interface HeaderObject extends ParameterBaseObject {}
  interface ParameterBaseObject {
    description?: string;
    required?: boolean;
    deprecated?: boolean;
    allowEmptyValue?: boolean;
    style?: string;
    explode?: boolean;
    allowReserved?: boolean;
    schema?: ReferenceObject | SchemaObject;
    example?: any;
    examples?: {
      [media: string]: ReferenceObject | ExampleObject;
    };
    content?: {
      [media: string]: MediaTypeObject;
    };
  }
  type NonArraySchemaObjectType =
    | "boolean"
    | "object"
    | "number"
    | "string"
    | "integer";
  type ArraySchemaObjectType = "array";
  type SchemaObject = ArraySchemaObject | NonArraySchemaObject;
  interface ArraySchemaObject extends BaseSchemaObject {
    type: ArraySchemaObjectType;
    items: ReferenceObject | SchemaObject;
  }
  interface NonArraySchemaObject extends BaseSchemaObject {
    type?: NonArraySchemaObjectType;
  }
  interface BaseSchemaObject {
    title?: string;
    description?: string;
    format?: string;
    default?: any;
    multipleOf?: number;
    maximum?: number;
    exclusiveMaximum?: boolean;
    minimum?: number;
    exclusiveMinimum?: boolean;
    maxLength?: number;
    minLength?: number;
    pattern?: string;
    additionalProperties?: boolean | ReferenceObject | SchemaObject;
    maxItems?: number;
    minItems?: number;
    uniqueItems?: boolean;
    maxProperties?: number;
    minProperties?: number;
    required?: string[];
    enum?: any[];
    properties?: {
      [name: string]: ReferenceObject | SchemaObject;
    };
    allOf?: (ReferenceObject | SchemaObject)[];
    oneOf?: (ReferenceObject | SchemaObject)[];
    anyOf?: (ReferenceObject | SchemaObject)[];
    not?: ReferenceObject | SchemaObject;
    nullable?: boolean;
    discriminator?: DiscriminatorObject;
    readOnly?: boolean;
    writeOnly?: boolean;
    xml?: XMLObject;
    externalDocs?: ExternalDocumentationObject;
    example?: any;
    deprecated?: boolean;
  }
  interface DiscriminatorObject {
    propertyName: string;
    mapping?: {
      [value: string]: string;
    };
  }
  interface XMLObject {
    name?: string;
    namespace?: string;
    prefix?: string;
    attribute?: boolean;
    wrapped?: boolean;
  }
  interface ReferenceObject {
    $ref: string;
  }
  interface ExampleObject {
    summary?: string;
    description?: string;
    value?: any;
    externalValue?: string;
  }
  interface MediaTypeObject {
    schema?: ReferenceObject | SchemaObject;
    example?: any;
    examples?: {
      [media: string]: ReferenceObject | ExampleObject;
    };
    encoding?: {
      [media: string]: EncodingObject;
    };
  }
  interface EncodingObject {
    contentType?: string;
    headers?: {
      [header: string]: ReferenceObject | HeaderObject;
    };
    style?: string;
    explode?: boolean;
    allowReserved?: boolean;
  }
  interface RequestBodyObject {
    description?: string;
    content: {
      [media: string]: MediaTypeObject;
    };
    required?: boolean;
  }
  interface ResponsesObject {
    [code: string]: ReferenceObject | ResponseObject;
  }
  interface ResponseObject {
    description: string;
    headers?: {
      [header: string]: ReferenceObject | HeaderObject;
    };
    content?: {
      [media: string]: MediaTypeObject;
    };
    links?: {
      [link: string]: ReferenceObject | LinkObject;
    };
  }
  interface LinkObject {
    operationRef?: string;
    operationId?: string;
    parameters?: {
      [parameter: string]: any;
    };
    requestBody?: any;
    description?: string;
    server?: ServerObject;
  }
  interface CallbackObject {
    [url: string]: PathItemObject;
  }
  interface SecurityRequirementObject {
    [name: string]: string[];
  }
  interface ComponentsObject {
    schemas?: {
      [key: string]: ReferenceObject | SchemaObject;
    };
    responses?: {
      [key: string]: ReferenceObject | ResponseObject;
    };
    parameters?: {
      [key: string]: ReferenceObject | ParameterObject;
    };
    examples?: {
      [key: string]: ReferenceObject | ExampleObject;
    };
    requestBodies?: {
      [key: string]: ReferenceObject | RequestBodyObject;
    };
    headers?: {
      [key: string]: ReferenceObject | HeaderObject;
    };
    securitySchemes?: {
      [key: string]: ReferenceObject | SecuritySchemeObject;
    };
    links?: {
      [key: string]: ReferenceObject | LinkObject;
    };
    callbacks?: {
      [key: string]: ReferenceObject | CallbackObject;
    };
  }
  type SecuritySchemeObject =
    | HttpSecurityScheme
    | ApiKeySecurityScheme
    | OAuth2SecurityScheme
    | OpenIdSecurityScheme;
  interface HttpSecurityScheme {
    type: "http";
    description?: string;
    scheme: string;
    bearerFormat?: string;
  }
  interface ApiKeySecurityScheme {
    type: "apiKey";
    description?: string;
    name: string;
    in: string;
  }
  interface OAuth2SecurityScheme {
    type: "oauth2";
    description?: string;
    flows: {
      implicit?: {
        authorizationUrl: string;
        refreshUrl?: string;
        scopes: {
          [scope: string]: string;
        };
      };
      password?: {
        tokenUrl: string;
        refreshUrl?: string;
        scopes: {
          [scope: string]: string;
        };
      };
      clientCredentials?: {
        tokenUrl: string;
        refreshUrl?: string;
        scopes: {
          [scope: string]: string;
        };
      };
      authorizationCode?: {
        authorizationUrl: string;
        tokenUrl: string;
        refreshUrl?: string;
        scopes: {
          [scope: string]: string;
        };
      };
    };
  }
  interface OpenIdSecurityScheme {
    type: "openIdConnect";
    description?: string;
    openIdConnectUrl: string;
  }
  interface TagObject {
    name: string;
    description?: string;
    externalDocs?: ExternalDocumentationObject;
  }
}

declare namespace OpenAPIV3_1 {
  type Modify<T, R> = Omit<T, keyof R> & R;
  type PathsWebhooksComponents<T extends {} = {}> = {
    paths: PathsObject<T>;
    webhooks: Record<string, PathItemObject | ReferenceObject>;
    components: ComponentsObject;
  };
  type Document<T extends {} = {}> = Modify<
    Omit<OpenAPIV3.Document<T>, "paths" | "components">,
    {
      info: InfoObject;
      jsonSchemaDialect?: string;
      servers?: ServerObject[];
    } & (
      | (Pick<PathsWebhooksComponents<T>, "paths"> &
          Omit<Partial<PathsWebhooksComponents<T>>, "paths">)
      | (Pick<PathsWebhooksComponents<T>, "webhooks"> &
          Omit<Partial<PathsWebhooksComponents<T>>, "webhooks">)
      | (Pick<PathsWebhooksComponents<T>, "components"> &
          Omit<Partial<PathsWebhooksComponents<T>>, "components">)
    )
  >;
  type InfoObject = Modify<
    OpenAPIV3.InfoObject,
    {
      summary?: string;
      license?: LicenseObject;
    }
  >;
  type ContactObject = OpenAPIV3.ContactObject;
  type LicenseObject = Modify<
    OpenAPIV3.LicenseObject,
    {
      identifier?: string;
    }
  >;
  type ServerObject = Modify<
    OpenAPIV3.ServerObject,
    {
      url: string;
      description?: string;
      variables?: Record<string, ServerVariableObject>;
    }
  >;
  type ServerVariableObject = Modify<
    OpenAPIV3.ServerVariableObject,
    {
      enum?: [string, ...string[]];
    }
  >;
  type PathsObject<T extends {} = {}, P extends {} = {}> = Record<
    string,
    (PathItemObject<T> & P) | undefined
  >;
  type HttpMethods = OpenAPIV3.HttpMethods;
  type PathItemObject<T extends {} = {}> = Modify<
    OpenAPIV3.PathItemObject<T>,
    {
      servers?: ServerObject[];
      parameters?: (ReferenceObject | ParameterObject)[];
    }
  > & {
    [method in HttpMethods]?: OperationObject<T>;
  };
  type OperationObject<T extends {} = {}> = Modify<
    OpenAPIV3.OperationObject<T>,
    {
      parameters?: (ReferenceObject | ParameterObject)[];
      requestBody?: ReferenceObject | RequestBodyObject;
      responses?: ResponsesObject;
      callbacks?: Record<string, ReferenceObject | CallbackObject>;
      servers?: ServerObject[];
    }
  > &
    T;
  type ExternalDocumentationObject = OpenAPIV3.ExternalDocumentationObject;
  type ParameterObject = OpenAPIV3.ParameterObject;
  type HeaderObject = OpenAPIV3.HeaderObject;
  type ParameterBaseObject = OpenAPIV3.ParameterBaseObject;
  type NonArraySchemaObjectType = OpenAPIV3.NonArraySchemaObjectType | "null";
  type ArraySchemaObjectType = OpenAPIV3.ArraySchemaObjectType;
  /**
   * There is no way to tell typescript to require items when type is either 'array' or array containing 'array' type
   * 'items' will be always visible as optional
   * Casting schema object to ArraySchemaObject or NonArraySchemaObject will work fine
   */
  type SchemaObject =
    | ArraySchemaObject
    | NonArraySchemaObject
    | MixedSchemaObject;
  interface ArraySchemaObject extends BaseSchemaObject {
    type: ArraySchemaObjectType;
    items: ReferenceObject | SchemaObject;
  }
  interface NonArraySchemaObject extends BaseSchemaObject {
    type?: NonArraySchemaObjectType;
  }
  interface MixedSchemaObject extends BaseSchemaObject {
    type?: (ArraySchemaObjectType | NonArraySchemaObjectType)[];
    items?: ReferenceObject | SchemaObject;
  }
  type BaseSchemaObject = Modify<
    Omit<OpenAPIV3.BaseSchemaObject, "nullable">,
    {
      examples?: OpenAPIV3.BaseSchemaObject["example"][];
      exclusiveMinimum?: boolean | number;
      exclusiveMaximum?: boolean | number;
      contentMediaType?: string;
      $schema?: string;
      additionalProperties?: boolean | ReferenceObject | SchemaObject;
      properties?: {
        [name: string]: ReferenceObject | SchemaObject;
      };
      allOf?: (ReferenceObject | SchemaObject)[];
      oneOf?: (ReferenceObject | SchemaObject)[];
      anyOf?: (ReferenceObject | SchemaObject)[];
      not?: ReferenceObject | SchemaObject;
      discriminator?: DiscriminatorObject;
      externalDocs?: ExternalDocumentationObject;
      xml?: XMLObject;
      const?: any;
    }
  >;
  type DiscriminatorObject = OpenAPIV3.DiscriminatorObject;
  type XMLObject = OpenAPIV3.XMLObject;
  type ReferenceObject = Modify<
    OpenAPIV3.ReferenceObject,
    {
      summary?: string;
      description?: string;
    }
  >;
  type ExampleObject = OpenAPIV3.ExampleObject;
  type MediaTypeObject = Modify<
    OpenAPIV3.MediaTypeObject,
    {
      schema?: SchemaObject | ReferenceObject;
      examples?: Record<string, ReferenceObject | ExampleObject>;
    }
  >;
  type EncodingObject = OpenAPIV3.EncodingObject;
  type RequestBodyObject = Modify<
    OpenAPIV3.RequestBodyObject,
    {
      content: {
        [media: string]: MediaTypeObject;
      };
    }
  >;
  type ResponsesObject = Record<string, ReferenceObject | ResponseObject>;
  type ResponseObject = Modify<
    OpenAPIV3.ResponseObject,
    {
      headers?: {
        [header: string]: ReferenceObject | HeaderObject;
      };
      content?: {
        [media: string]: MediaTypeObject;
      };
      links?: {
        [link: string]: ReferenceObject | LinkObject;
      };
    }
  >;
  type LinkObject = Modify<
    OpenAPIV3.LinkObject,
    {
      server?: ServerObject;
    }
  >;
  type CallbackObject = Record<string, PathItemObject | ReferenceObject>;
  type SecurityRequirementObject = OpenAPIV3.SecurityRequirementObject;
  type ComponentsObject = Modify<
    OpenAPIV3.ComponentsObject,
    {
      schemas?: Record<string, SchemaObject>;
      responses?: Record<string, ReferenceObject | ResponseObject>;
      parameters?: Record<string, ReferenceObject | ParameterObject>;
      examples?: Record<string, ReferenceObject | ExampleObject>;
      requestBodies?: Record<string, ReferenceObject | RequestBodyObject>;
      headers?: Record<string, ReferenceObject | HeaderObject>;
      securitySchemes?: Record<string, ReferenceObject | SecuritySchemeObject>;
      links?: Record<string, ReferenceObject | LinkObject>;
      callbacks?: Record<string, ReferenceObject | CallbackObject>;
      pathItems?: Record<string, ReferenceObject | PathItemObject>;
    }
  >;
  type SecuritySchemeObject = OpenAPIV3.SecuritySchemeObject;
  type HttpSecurityScheme = OpenAPIV3.HttpSecurityScheme;
  type ApiKeySecurityScheme = OpenAPIV3.ApiKeySecurityScheme;
  type OAuth2SecurityScheme = OpenAPIV3.OAuth2SecurityScheme;
  type OpenIdSecurityScheme = OpenAPIV3.OpenIdSecurityScheme;
  type TagObject = OpenAPIV3.TagObject;
  export {};
}

/**
 * Base object for parameter definitions
 * @public
 */
declare type ParameterBaseObject = Modify<
  Omit<
    OpenAPIV3_1.ParameterBaseObject,
    | "content"
    | "allowEmptyValue"
    | "style"
    | "allowReserved"
    | "explode"
    | "example"
    | "examples"
  >,
  {
    schema: OpenAPIV3_1.SchemaObject;
  }
>;

/**
 * Definition of a parameter
 * @public
 */
declare interface ParameterDefinition extends ParameterBaseObject {
  name: string;
  in: string;
}

/**
 * Runs only if its handler's verdict wins, after the inbound chain has
 * stopped — the one place a pre-request handler may touch shared context
 * state. Resolve a `Response` to serve it, or `undefined` to withdraw the
 * verdict and let the pipeline proceed.
 * @beta
 */
declare interface PreRequestCommit {
  (): Promise<Response | undefined>;
}

/**
 * Work started by an inbound policy that runs concurrently with the rest of
 * the inbound policy chain. Registered with
 * {@link ZuploContext.addPreRequestHandler}, started immediately.
 *
 * Resolve `undefined` to let the request proceed, a `Response` to
 * short-circuit the pipeline with it, or a {@link PreRequestCommit} for a
 * verdict that needs exclusive serve-time work.
 *
 * Handlers run out of order relative to the policies they overlap, so they
 * must never mutate or consume the live request — capture what they need
 * (for example via `request.clone()`) before registering.
 * @beta
 */
declare interface PreRequestHandler {
  (api: PreRequestHandlerApi): Promise<Response | PreRequestCommit | undefined>;
}

/**
 * The API handed to a {@link PreRequestHandler} when it starts.
 * @beta
 */
declare interface PreRequestHandlerApi {
  /**
   * Aborted when this handler's verdict can no longer win — another verdict
   * was served, or the pipeline resolved with the chain's own response or an
   * error. Pass it to `fetch()` so the external call is actually cancelled.
   */
  readonly signal: AbortSignal;
}

/**
 * Generic type parameters for a request.
 * Extends RequestInitGeneric and adds query parameter typing.
 * @public
 */
declare interface RequestGeneric extends RequestInitGeneric {
  Query?: RequestQueryDefault;
}

/**
 * Generic type parameters for request initialization.
 * Used to strongly type the user data and path parameters.
 * @public
 */
declare interface RequestInitGeneric {
  UserData?: UserDataDefault;
  Params?: RequestParamsDefault;
}

declare type RequestParamsDefault = Record<string, string>;

declare type RequestQueryDefault = Record<string, string>;

/**
 * Represents an authenticated user on the request.
 * Set by authentication policies like API key, JWT, or OAuth.
 *
 * @public
 * @example
 * ```typescript
 * // Access user info in a handler
 * export function myHandler(request: ZuploRequest, context: ZuploContext) {
 *   if (!request.user) {
 *     return new Response("Unauthorized", { status: 401 });
 *   }
 *
 *   const userId = request.user.sub;
 *   const customData = request.user.data as { role: string; tenantId: string };
 *
 *   context.log.info(`Request from user ${userId} with role ${customData.role}`);
 * }
 * ```
 */
declare interface RequestUser<TUserData> {
  sub: string;
  data: TUserData;
}

declare type ResolveRequestParams<
  TParams extends RequestParamsDefault | undefined,
> = TParams extends RequestParamsDefault ? TParams : RequestParamsDefault;

declare type ResolveRequestQuery<
  TQuery extends RequestQueryDefault | undefined,
> = TQuery extends RequestQueryDefault ? TQuery : RequestQueryDefault;

declare type ResolveUserData<TUserData extends UserDataDefault | undefined> =
  TUserData extends UserDataDefault ? TUserData : UserDataDefault;

/**
 * Definition of responses for a route
 * @public
 */
declare type ResponsesDefinition = Record<
  HttpStatusCode | HttpStatusCodeRangeDefinition,
  Modify<
    Omit<OpenAPIV3_1.ResponseObject, "links">,
    {
      headers?: {
        [header: string]: ParameterBaseObject;
      };
    }
  >
>;

/**
 * @public
 */
declare interface RouteConfiguration extends Omit<
  BuildRouteConfiguration,
  "raw"
> {
  /**
   * @deprecated Please switch to "raw().operationId"
   */
  operationId?: string;
  /**
   * @deprecated Please switch to "raw().summary"
   */
  summary?: string;
  /**
   * @deprecated Please switch to "raw().tags"
   */
  tags?: string[];
  /**
   * @deprecated Please switch to "raw().parameters"
   */
  parameters?: ParameterDefinition[];
  /**
   * @deprecated Please switch to "raw().responses"
   */
  responses?: ResponsesDefinition;
  /**
   * Gets the raw route configuration object
   */
  raw<T = any>(): T;
}

/**
 * Registers an AWS credential provider on the request context. Called by the
 * upstream AWS auth policies so that AWS-aware handlers (the AWS Lambda
 * handler) and custom code can sign requests without re-resolving credentials.
 *
 * @beta
 * @param context - The current ZuploContext
 * @param provider - A provider that resolves and refreshes AWS credentials
 */
export declare function setAwsCredentialProvider(
  context: ZuploContext,
  provider: AwsCredentialProvider
): void;

/**
 * Signs an existing {@link Request} with AWS Signature Version 4 and returns a
 * new Request carrying the signature (Authorization, X-Amz-Date and, for
 * temporary credentials, X-Amz-Security-Token headers — or query parameters
 * when `signQuery` is set).
 *
 * The request body is buffered to compute the payload hash. Complements
 * {@link AwsClient.fetch} for callers that build and send their own fetch.
 *
 * @beta
 * @example
 * ```typescript
 * import { signRequest, getAwsCredentialProvider } from "@zuplo/runtime/aws";
 *
 * const provider = getAwsCredentialProvider(context)!;
 * const signed = await signRequest(
 *   new Request("https://abc.execute-api.us-east-1.amazonaws.com/prod/thing"),
 *   { credentials: provider }
 * );
 * const response = await fetch(signed);
 * ```
 */
export declare function signRequest(
  request: Request,
  options: SignRequestOptions
): Promise<Request>;

/**
 * Options for {@link signRequest}.
 * @beta
 */
export declare interface SignRequestOptions {
  /** The credentials (or a provider) to sign with. */
  credentials: AwsCredentials | AwsCredentialProvider;
  /**
   * The AWS service name (e.g. "execute-api", "s3", "lambda"). If omitted, it
   * is derived from the request hostname.
   */
  service?: string;
  /**
   * The AWS region. If omitted, it is derived from the request hostname
   * (falling back to "us-east-1").
   */
  region?: string;
  /**
   * Sign using query-string parameters (presigned-URL style) instead of the
   * Authorization header.
   */
  signQuery?: boolean;
}

/**
 * Retry configuration shared across the cloud auth SDKs. Token and credential
 * requests are retried on 5xx/429 responses and network errors using
 * exponential backoff.
 *
 * @beta
 */
export declare interface TokenRetryOptions {
  /**
   * The maximum number of times to retry a failed request. Defaults to 3.
   */
  retries?: number;
  /**
   * The base delay in milliseconds between retries. The actual delay uses
   * exponential backoff (`retryDelayMs * 2^attempt`). Defaults to 10.
   */
  retryDelayMs?: number;
}

declare type UserDataDefault = any;

/**
 * @public
 */
declare interface WaitUntilFunc {
  (promise: Promise<any>): void;
}

declare interface ZuploAnalyticsContext {
  addAnalyticsEvent(
    value: number,
    eventType: EventType,
    metadata: JsonObject,
    unit?: string,
    eventId?: string
  ): void;
  flushAnalyticsEvents(): ZuploAnalyticsEvent[];
  getAnalyticsEvents(): ZuploAnalyticsEvent[];
}

declare interface ZuploAnalyticsEvent<T extends JsonObject = JsonObject> {
  eventId: string;
  requestId: string;
  timestamp: Date;
  accountName: string;
  projectName: string;
  deploymentName: string;
  eventType: EventType;
  metadata: T;
  unit?: string;
  value: number;
}

/**
 * The ZuploContext provides information about the current request and helper methods.
 * @public
 */
declare interface ZuploContext extends EventTarget {
  /**
   * The unique identifier of this context
   */
  readonly contextId: Readonly<string>;
  /**
   * The unique identifier of the incoming request
   */
  readonly requestId: Readonly<string>;
  /**
   * Request based logger
   */
  readonly log: Readonly<Logger>;
  /**
   * The route that is being processed
   */
  readonly route: Readonly<RouteConfiguration>;
  /**
   * Custom data stored on the ZuploContext
   */
  readonly custom: Record<string, any>;
  readonly incomingRequestProperties: IncomingRequestProperties;
  /**
   * The parent context that spawned this context
   * @beta
   */
  readonly parentContext: ZuploContext | undefined;
  /* Excluded from this release type: analyticsContext */
  readonly invokeInboundPolicy: (
    policyName: string,
    request: ZuploRequest
  ) => Promise<Response | ZuploRequest>;
  readonly invokeOutboundPolicy: (
    policyName: string,
    response: Response,
    request: ZuploRequest
  ) => Promise<Response>;
  /**
   * Invokes a route based on a Request without going back out to HTTP.
   * Can take a relative route path to invoke on the Gateway
   * Example: "/my/route" will invoke http://localhost/my/route on the Gateway
   * without having to rebuild the Request's protocol and host.
   * @beta
   */
  readonly invokeRoute: <TOptions extends RequestGeneric = RequestGeneric>(
    input: string | URL | Request,
    init?: ZuploRequestInit<TOptions>
  ) => Promise<Response>;
  readonly waitUntil: WaitUntilFunc;
  /**
   * Fires just before the response is sent. Response can be modified.
   */
  readonly addResponseSendingHook: (hook: OnResponseSendingHook) => void;
  /**
   * Fires immediately after the response is sent. Response cannot be modified.
   */
  readonly addResponseSendingFinalHook: (
    hook: OnResponseSendingFinalHook
  ) => void;
  /**
   * Registers a pre-request handler: work started immediately that runs
   * concurrently with the remaining inbound policy chain.
   *
   * The runtime checks the handler after each subsequent policy completes and
   * serves its `Response` verdict if one has resolved (skipping the remaining
   * policies, the route handler, and outbound policies). All outstanding
   * handlers are awaited at a barrier just before the route handler dispatches
   * upstream — the only point in the pipeline that blocks on a handler. A
   * response produced by the policy chain itself (for example an
   * authentication policy's 401) is served immediately: already-resolved
   * verdicts from earlier-registered handlers still win, but a pending
   * handler never delays it and is aborted instead.
   *
   * Handlers run out of order relative to the policies they overlap, so they
   * must observe and veto, never transform: do not mutate or consume the live
   * request from a handler. A handler that rejects fails the request closed
   * (500); catch inside the handler and resolve `undefined` to fail open.
   *
   * May only be called during the inbound policy phase.
   * @beta
   */
  readonly addPreRequestHandler: (
    handler: PreRequestHandler,
    options?: {
      name?: string;
    }
  ) => void;
  /**
   * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
   *
   * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.
   *
   * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
   *
   * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
   *
   * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
   *
   * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.
   *
   * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.
   * @deprecated This will be removed in the future. Use hooks instead. See {@link https://zuplo.com/docs/programmable-api/runtime-extensions}
   */
  addEventListener<Type extends keyof Record<string, Event>>(
    type: Type,
    handler: EventListenerOrEventListenerObject,
    options?: AddEventListenerOptions | boolean
  ): void;
  /**
   * @deprecated This will be removed in the future. See {@link https://zuplo.com/docs/programmable-api/runtime-extensions}
   */
  removeEventListener<Type extends keyof Record<string, Event>>(
    type: Type,
    handler: EventListenerOrEventListenerObject,
    options?: AddEventListenerOptions | boolean
  ): void;
}

/**
 * Enhanced Request class that extends the standard Web Request API with
 * convenient properties for accessing path parameters, query strings, and user data.
 * This is the request type passed to all handlers and policies in Zuplo.
 *
 * @public
 * @example
 * ```typescript
 * import { ZuploRequest, ZuploContext } from "@zuplo/runtime";
 *
 * export function myHandler(request: ZuploRequest, context: ZuploContext) {
 *   // Access query parameters
 *   const page = request.query.page || "1";
 *   const limit = request.query.limit || "10";
 *
 *   // Access path parameters (e.g., from /users/:userId)
 *   const userId = request.params.userId;
 *
 *   // Access authenticated user
 *   const user = request.user;
 *
 *   // Standard Request properties still available
 *   const contentType = request.headers.get("content-type");
 *   const method = request.method;
 *
 *   return Response.json({
 *     userId,
 *     page,
 *     limit,
 *     authenticated: !!user
 *   });
 * }
 * ```
 *
 * @example
 * ```typescript
 * // Strongly typed request parameters
 * interface MyParams {
 *   userId: string;
 *   orderId: string;
 * }
 *
 * interface MyQuery {
 *   include?: string;
 *   format?: "json" | "xml";
 * }
 *
 * interface MyUserData {
 *   role: "admin" | "user";
 *   tenantId: string;
 * }
 *
 * type MyRequest = ZuploRequest<{
 *   Params: MyParams;
 *   Query: MyQuery;
 *   UserData: MyUserData;
 * }>;
 *
 * export function typedHandler(request: MyRequest, context: ZuploContext) {
 *   // All properties are now strongly typed
 *   const userId = request.params.userId; // string
 *   const format = request.query.format; // "json" | "xml" | undefined
 *   const role = request.user?.data.role; // "admin" | "user" | undefined
 * }
 * ```
 */
declare class ZuploRequest<
  TOptions extends RequestGeneric = RequestGeneric,
> extends Request {
  #private;
  constructor(
    input: string | URL | Request,
    init?: ZuploRequestInit<TOptions>,
    originalRequest?: Request
  );
  /* Excluded from this release type: originalRequest */
  /**
   * A dictionary of query-string values
   *
   * @example
   * The url `https://example.com?foo=bar` would return
   * the following query object:
   *
   * ```
   * const foo = request.query.foo;
   * ```
   *
   * @readonly
   */
  get query(): Readonly<ResolveRequestQuery<TOptions["Query"]>>;
  /**
   * If you use tokens in your route’s URL, they are
   * automatically parsed into properties on the params
   * property of your request.
   *
   * @example
   * The route `/products/:productId/vendors/:vendorId`
   * would include two params:
   *
   * ```
   * const productId = request.params.productId;
   * const vendorId = request.params.vendorId;
   * ```
   * @readonly
   */
  get params(): Readonly<ResolveRequestParams<TOptions["Params"]>>;
  /**
   * An optional object identifying a ‘user’.
   *
   * @remarks
   * If undefined this typically means the request is
   * anonymous. If present, the user object will have
   * a sub property that is a unique identifier for
   * that user. There is also an optional data property
   * that is of any type that typically contains other
   * information about the user. When using JWT tokens
   * you’ll usually find all the claims here.
   *
   * @readonly
   */
  user?: RequestUser<ResolveUserData<TOptions["UserData"]>>;
}

/**
 * Options for creating a new ZuploRequest.
 * Extends the standard RequestInit with Zuplo-specific properties.
 * @public
 */
declare interface ZuploRequestInit<
  TOptions extends RequestInitGeneric = RequestInitGeneric,
> extends RequestInit {
  params?: ResolveRequestParams<TOptions["Params"]>;
  user?: ResolveUserData<TOptions["UserData"]>;
}

export {};
