{"version":3,"sources":["../lib/index.ts","../lib/AccessTokenClient.ts","../lib/MetadataClientV1_0_13.ts","../lib/functions/AuthorizationUtil.ts","../lib/functions/notifications.ts","../lib/types/index.ts","../lib/functions/OpenIDUtils.ts","../lib/functions/AccessTokenUtil.ts","../lib/ProofOfPossessionBuilder.ts","../lib/functions/CredentialOfferCommons.ts","../lib/functions/dpopUtil.ts","../lib/AccessTokenClientV1_0_11.ts","../lib/AuthorizationCodeClient.ts","../lib/MetadataClient.ts","../lib/MetadataClientV1_0_11.ts","../lib/AuthorizationCodeClientV1_0_11.ts","../lib/CredentialRequestClient.ts","../lib/CredentialOfferClient.ts","../lib/CredentialOfferClientV1_0_11.ts","../lib/CredentialOfferClientV1_0_13.ts","../lib/CredentialRequestClientV1_0_11.ts","../lib/CredentialRequestClientBuilder.ts","../lib/CredentialRequestClientBuilderV1_0_11.ts","../lib/CredentialRequestClientBuilderV1_0_13.ts","../lib/OpenID4VCIClient.ts","../lib/OpenID4VCIClientV1_0_13.ts","../lib/OpenID4VCIClientV1_0_11.ts"],"sourcesContent":["import { VCI_LOGGERS } from '@sphereon/oid4vci-common'\nimport { ISimpleLogger } from '@sphereon/ssi-types'\n\nexport const LOG: ISimpleLogger<string> = VCI_LOGGERS.get('sphereon:oid4vci:client')\n\nexport * from './AccessTokenClient'\nexport * from './AccessTokenClientV1_0_11'\nexport * from './AuthorizationCodeClient'\nexport * from './AuthorizationCodeClientV1_0_11'\nexport * from './CredentialRequestClient'\nexport * from './CredentialOfferClient'\nexport * from './CredentialOfferClientV1_0_11'\nexport * from './CredentialOfferClientV1_0_13'\nexport * from './CredentialRequestClientV1_0_11'\nexport * from './CredentialRequestClientBuilder'\nexport * from './CredentialRequestClientBuilderV1_0_13'\nexport * from './CredentialRequestClientBuilderV1_0_11'\nexport * from './functions'\nexport * from './MetadataClient'\nexport * from './MetadataClientV1_0_13'\nexport * from './MetadataClientV1_0_11'\nexport * from './OpenID4VCIClient'\nexport * from './OpenID4VCIClientV1_0_13'\nexport * from './OpenID4VCIClientV1_0_11'\nexport * from './ProofOfPossessionBuilder'\n","import { createDPoP, CreateDPoPClientOpts, getCreateDPoPOptions } from '@sphereon/oid4vc-common'\nimport {\n  AccessTokenRequest,\n  AccessTokenRequestOpts,\n  AccessTokenResponse,\n  assertedUniformCredentialOffer,\n  AuthorizationServerOpts,\n  AuthzFlowType,\n  convertJsonToURI,\n  DPoPResponseParams,\n  EndpointMetadata,\n  formPost,\n  getIssuerFromCredentialOfferPayload,\n  GrantTypes,\n  IssuerOpts,\n  JsonURIMode,\n  OpenIDResponse,\n  PRE_AUTH_CODE_LITERAL,\n  PRE_AUTH_GRANT_LITERAL,\n  TokenErrorResponse,\n  toUniformCredentialOfferRequest,\n  TxCodeAndPinRequired,\n  UniformCredentialOfferPayload,\n} from '@sphereon/oid4vci-common'\nimport { ObjectUtils } from '@sphereon/ssi-types'\n\nimport { MetadataClientV1_0_13 } from './MetadataClientV1_0_13'\nimport { createJwtBearerClientAssertion } from './functions'\nimport { shouldRetryTokenRequestWithDPoPNonce } from './functions/dpopUtil'\nimport { LOG } from './types'\n\nexport class AccessTokenClient {\n  public async acquireAccessToken(opts: AccessTokenRequestOpts): Promise<OpenIDResponse<AccessTokenResponse, DPoPResponseParams>> {\n    const { asOpts, pin, codeVerifier, code, redirectUri, metadata, createDPoPOpts } = opts\n\n    const credentialOffer = opts.credentialOffer ? await assertedUniformCredentialOffer(opts.credentialOffer) : undefined\n    const pinMetadata: TxCodeAndPinRequired | undefined = credentialOffer && this.getPinMetadata(credentialOffer.credential_offer)\n    const issuer =\n      opts.credentialIssuer ??\n      (credentialOffer ? getIssuerFromCredentialOfferPayload(credentialOffer.credential_offer) : (metadata?.issuer as string))\n    if (!issuer) {\n      throw Error('Issuer required at this point')\n    }\n    const issuerOpts = {\n      issuer,\n    }\n\n    return await this.acquireAccessTokenUsingRequest({\n      accessTokenRequest: await this.createAccessTokenRequest({\n        credentialOffer,\n        asOpts,\n        codeVerifier,\n        code,\n        redirectUri,\n        pin,\n        credentialIssuer: issuer,\n        metadata,\n        additionalParams: opts.additionalParams,\n        pinMetadata,\n      }),\n      pinMetadata,\n      metadata,\n      asOpts,\n      issuerOpts,\n      createDPoPOpts: createDPoPOpts,\n    })\n  }\n\n  public async acquireAccessTokenUsingRequest({\n    accessTokenRequest,\n    pinMetadata,\n    metadata,\n    asOpts,\n    issuerOpts,\n    createDPoPOpts,\n  }: {\n    accessTokenRequest: AccessTokenRequest\n    pinMetadata?: TxCodeAndPinRequired\n    metadata?: EndpointMetadata\n    asOpts?: AuthorizationServerOpts\n    issuerOpts?: IssuerOpts\n    createDPoPOpts?: CreateDPoPClientOpts\n  }): Promise<OpenIDResponse<AccessTokenResponse, DPoPResponseParams>> {\n    this.validate(accessTokenRequest, pinMetadata)\n\n    const requestTokenURL = AccessTokenClient.determineTokenURL({\n      asOpts,\n      issuerOpts,\n      metadata: metadata\n        ? metadata\n        : issuerOpts?.fetchMetadata\n          ? await MetadataClientV1_0_13.retrieveAllMetadata(issuerOpts.issuer, { errorOnNotFound: false })\n          : undefined,\n    })\n\n    const useDpop = createDPoPOpts?.dPoPSigningAlgValuesSupported && createDPoPOpts.dPoPSigningAlgValuesSupported.length > 0\n    let dPoP = useDpop ? await createDPoP(getCreateDPoPOptions(createDPoPOpts, requestTokenURL)) : undefined\n\n    let response = await this.sendAuthCode(requestTokenURL, accessTokenRequest, dPoP ? { headers: { dpop: dPoP } } : undefined)\n\n    let nextDPoPNonce = createDPoPOpts?.jwtPayloadProps.nonce\n    const retryWithNonce = shouldRetryTokenRequestWithDPoPNonce(response)\n    if (retryWithNonce.ok && createDPoPOpts) {\n      createDPoPOpts.jwtPayloadProps.nonce = retryWithNonce.dpopNonce\n\n      dPoP = await createDPoP(getCreateDPoPOptions(createDPoPOpts, requestTokenURL))\n      response = await this.sendAuthCode(requestTokenURL, accessTokenRequest, dPoP ? { headers: { dpop: dPoP } } : undefined)\n      const successDPoPNonce = response.origResponse.headers.get('DPoP-Nonce')\n\n      nextDPoPNonce = successDPoPNonce ?? retryWithNonce.dpopNonce\n    }\n\n    if (response.successBody && createDPoPOpts && response.successBody.token_type !== 'DPoP') {\n      throw new Error('Invalid token type returned. Expected DPoP. Received: ' + response.successBody.token_type)\n    }\n\n    return {\n      ...response,\n      ...(nextDPoPNonce && { params: { dpop: { dpopNonce: nextDPoPNonce } } }),\n    }\n  }\n\n  public async createAccessTokenRequest(opts: Omit<AccessTokenRequestOpts, 'createDPoPOpts'>): Promise<AccessTokenRequest> {\n    const { asOpts, pin, codeVerifier, code, redirectUri } = opts\n    // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n    // @ts-ignore\n    const credentialOfferRequest = opts.credentialOffer ? await toUniformCredentialOfferRequest(opts.credentialOffer) : undefined\n    const request: Partial<AccessTokenRequest> = { ...opts.additionalParams }\n    if (asOpts?.clientOpts?.clientId) {\n      request.client_id = asOpts.clientOpts.clientId\n    }\n    const credentialIssuer = opts.credentialIssuer ?? credentialOfferRequest?.credential_offer?.credential_issuer ?? opts.metadata?.issuer\n    await createJwtBearerClientAssertion(request, { ...opts, credentialIssuer })\n\n    // Prefer AUTHORIZATION_CODE over PRE_AUTHORIZED_CODE_FLOW\n    if (!credentialOfferRequest || credentialOfferRequest.supportedFlows.includes(AuthzFlowType.AUTHORIZATION_CODE_FLOW)) {\n      request.grant_type = GrantTypes.AUTHORIZATION_CODE\n      request.code = code\n      request.redirect_uri = redirectUri\n\n      if (codeVerifier) {\n        request.code_verifier = codeVerifier\n      }\n\n      return request as AccessTokenRequest\n    }\n\n    if (credentialOfferRequest?.supportedFlows.includes(AuthzFlowType.PRE_AUTHORIZED_CODE_FLOW)) {\n      this.assertAlphanumericPin(opts.pinMetadata, pin)\n      request.user_pin = pin\n      request.tx_code = pin\n\n      request.grant_type = GrantTypes.PRE_AUTHORIZED_CODE\n      // we actually know it is there because of the isPreAuthCode call\n      request[PRE_AUTH_CODE_LITERAL] = credentialOfferRequest?.credential_offer.grants?.[PRE_AUTH_GRANT_LITERAL]?.[PRE_AUTH_CODE_LITERAL]\n\n      return request as AccessTokenRequest\n    }\n\n    throw new Error('Credential offer request follows neither pre-authorized code nor authorization code flow requirements.')\n  }\n\n  private assertPreAuthorizedGrantType(grantType: GrantTypes): void {\n    if (GrantTypes.PRE_AUTHORIZED_CODE !== grantType) {\n      throw new Error(\"grant type must be 'urn:ietf:params:oauth:grant-type:pre-authorized_code'\")\n    }\n  }\n\n  private assertAuthorizationGrantType(grantType: GrantTypes): void {\n    if (GrantTypes.AUTHORIZATION_CODE !== grantType) {\n      throw new Error(\"grant type must be 'authorization_code'\")\n    }\n  }\n\n  private getPinMetadata(requestPayload: UniformCredentialOfferPayload): TxCodeAndPinRequired {\n    if (!requestPayload) {\n      throw new Error(TokenErrorResponse.invalid_request)\n    }\n    const issuer = getIssuerFromCredentialOfferPayload(requestPayload)\n\n    const grantDetails = requestPayload.grants?.[PRE_AUTH_GRANT_LITERAL]\n    const isPinRequired = !!(grantDetails?.tx_code ?? false)\n\n    LOG.warning(`Pin required for issuer ${issuer}: ${isPinRequired}`)\n    return {\n      txCode: grantDetails?.tx_code,\n      isPinRequired,\n    }\n  }\n\n  private assertAlphanumericPin(pinMeta?: TxCodeAndPinRequired, pin?: string): void {\n    if (pinMeta && pinMeta.isPinRequired) {\n      let regex\n\n      if (pinMeta.txCode) {\n        const { input_mode, length } = pinMeta.txCode\n\n        if (input_mode === 'numeric') {\n          // Create a regex for numeric input. If no length specified, allow any length of numeric input.\n          regex = length ? new RegExp(`^\\\\d{1,${length}}$`) : /^\\d+$/\n        } else if (input_mode === 'text') {\n          // Create a regex for text input. If no length specified, allow any length of alphanumeric input.\n          regex = length ? new RegExp(`^[a-zA-Z0-9]{1,${length}}$`) : /^[a-zA-Z0-9]+$/\n        }\n      }\n\n      // Default regex for alphanumeric with no specific length limit if no input_mode is specified.\n      regex = regex || /^[a-zA-Z0-9]+$|^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+$/\n\n      if (!pin || !regex.test(pin)) {\n        LOG.warning(\n          `Pin is not valid. Expected format: ${pinMeta?.txCode?.input_mode || 'alphanumeric'}, Length: up to ${pinMeta?.txCode?.length || 'any number of'} characters`,\n        )\n        throw new Error('A valid pin must be present according to the specified transaction code requirements.')\n      }\n    } else if (pin) {\n      LOG.warning('Pin set, whilst not required')\n      throw new Error('Cannot set a pin when the pin is not required.')\n    }\n  }\n\n  private assertNonEmptyPreAuthorizedCode(accessTokenRequest: AccessTokenRequest): void {\n    if (!accessTokenRequest[PRE_AUTH_CODE_LITERAL]) {\n      LOG.warning(`No pre-authorized code present, whilst it is required`, accessTokenRequest)\n      throw new Error('Pre-authorization must be proven by presenting the pre-authorized code. Code must be present.')\n    }\n  }\n\n  private assertNonEmptyCodeVerifier(accessTokenRequest: AccessTokenRequest): void {\n    if (!accessTokenRequest.code_verifier) {\n      LOG.warning('No code_verifier present, whilst it is required', accessTokenRequest)\n      throw new Error('Authorization flow requires the code_verifier to be present')\n    }\n  }\n\n  private assertNonEmptyCode(accessTokenRequest: AccessTokenRequest): void {\n    if (!accessTokenRequest.code) {\n      LOG.warning('No code present, whilst it is required')\n      throw new Error('Authorization flow requires the code to be present')\n    }\n  }\n\n  private validate(accessTokenRequest: AccessTokenRequest, pinMeta?: TxCodeAndPinRequired): void {\n    if (accessTokenRequest.grant_type === GrantTypes.PRE_AUTHORIZED_CODE) {\n      this.assertPreAuthorizedGrantType(accessTokenRequest.grant_type)\n      this.assertNonEmptyPreAuthorizedCode(accessTokenRequest)\n      this.assertAlphanumericPin(pinMeta, accessTokenRequest.tx_code ?? accessTokenRequest.user_pin)\n    } else if (accessTokenRequest.grant_type === GrantTypes.AUTHORIZATION_CODE) {\n      this.assertAuthorizationGrantType(accessTokenRequest.grant_type)\n      this.assertNonEmptyCodeVerifier(accessTokenRequest)\n      this.assertNonEmptyCode(accessTokenRequest)\n    } else {\n      this.throwNotSupportedFlow()\n    }\n  }\n\n  private async sendAuthCode(\n    requestTokenURL: string,\n    accessTokenRequest: AccessTokenRequest,\n    opts?: { headers?: Record<string, string> },\n  ): Promise<OpenIDResponse<AccessTokenResponse, DPoPResponseParams>> {\n    return await formPost(requestTokenURL, convertJsonToURI(accessTokenRequest, { mode: JsonURIMode.X_FORM_WWW_URLENCODED }), {\n      customHeaders: opts?.headers ? opts.headers : undefined,\n    })\n  }\n\n  public static determineTokenURL({\n    asOpts,\n    issuerOpts,\n    metadata,\n  }: {\n    asOpts?: AuthorizationServerOpts\n    issuerOpts?: IssuerOpts\n    metadata?: EndpointMetadata\n  }): string {\n    if (!asOpts && !metadata?.token_endpoint && !issuerOpts) {\n      throw new Error('Cannot determine token URL if no issuer, metadata and no Authorization Server values are present')\n    }\n    let url\n    if (asOpts && asOpts.as) {\n      url = this.creatTokenURLFromURL(asOpts.as, asOpts?.allowInsecureEndpoints, asOpts.tokenEndpoint)\n    } else if (metadata?.token_endpoint) {\n      url = metadata.token_endpoint\n    } else {\n      if (!issuerOpts?.issuer) {\n        throw Error('Either authorization server options, a token endpoint or issuer options are required at this point')\n      }\n      url = this.creatTokenURLFromURL(issuerOpts.issuer, asOpts?.allowInsecureEndpoints, issuerOpts.tokenEndpoint)\n    }\n\n    if (!url || !ObjectUtils.isString(url)) {\n      throw new Error('No authorization server token URL present. Cannot acquire access token')\n    }\n    LOG.debug(`Token endpoint determined to be ${url}`)\n    return url\n  }\n\n  private static creatTokenURLFromURL(url: string, allowInsecureEndpoints?: boolean, tokenEndpoint?: string): string {\n    if (allowInsecureEndpoints !== true && url.startsWith('http:')) {\n      throw Error(\n        `Unprotected token endpoints are not allowed ${url}. Use the 'allowInsecureEndpoints' param if you really need this for dev/testing!`,\n      )\n    }\n    const hostname = url.replace(/https?:\\/\\//, '').replace(/\\/$/, '')\n    const endpoint = tokenEndpoint ? (tokenEndpoint.startsWith('/') ? tokenEndpoint : tokenEndpoint.substring(1)) : '/token'\n    const scheme = url.split('://')[0]\n    return `${scheme ? scheme + '://' : 'https://'}${hostname}${endpoint}`\n  }\n\n  private throwNotSupportedFlow(): void {\n    LOG.warning(`Only pre-authorized or authorization code flows supported.`)\n    throw new Error('Only pre-authorized-code or authorization code flows are supported')\n  }\n}\n","import {\n  AuthorizationServerMetadata,\n  AuthorizationServerType,\n  CredentialIssuerMetadataV1_0_13,\n  CredentialOfferPayloadV1_0_13,\n  CredentialOfferRequestWithBaseUrl,\n  EndpointMetadataResultV1_0_13,\n  getIssuerFromCredentialOfferPayload,\n  IssuerMetadataV1_0_13,\n  OpenIDResponse,\n  WellKnownEndpoints,\n} from '@sphereon/oid4vci-common'\nimport { Loggers } from '@sphereon/ssi-types'\n\nimport { retrieveWellknown } from './functions'\nconst logger = Loggers.DEFAULT.get('sphereon:oid4vci:metadata')\n\nexport class MetadataClientV1_0_13 {\n  /**\n   * Retrieve metadata using the Initiation obtained from a previous step\n   *\n   * @param credentialOffer\n   */\n  public static async retrieveAllMetadataFromCredentialOffer(\n    credentialOffer: CredentialOfferRequestWithBaseUrl,\n  ): Promise<EndpointMetadataResultV1_0_13> {\n    return MetadataClientV1_0_13.retrieveAllMetadataFromCredentialOfferRequest(credentialOffer.credential_offer as CredentialOfferPayloadV1_0_13)\n  }\n\n  /**\n   * Retrieve the metada using the initiation request obtained from a previous step\n   * @param request\n   */\n  public static async retrieveAllMetadataFromCredentialOfferRequest(request: CredentialOfferPayloadV1_0_13): Promise<EndpointMetadataResultV1_0_13> {\n    const issuer = getIssuerFromCredentialOfferPayload(request)\n    if (issuer) {\n      return MetadataClientV1_0_13.retrieveAllMetadata(issuer)\n    }\n    throw new Error(\"can't retrieve metadata from CredentialOfferRequest. No issuer field is present\")\n  }\n\n  /**\n   * Retrieve all metadata from an issuer\n   * @param issuer The issuer URL\n   * @param opts\n   */\n  public static async retrieveAllMetadata(issuer: string, opts?: { errorOnNotFound: boolean }): Promise<EndpointMetadataResultV1_0_13> {\n    let token_endpoint: string | undefined\n    let credential_endpoint: string | undefined\n    let deferred_credential_endpoint: string | undefined\n    let authorization_endpoint: string | undefined\n    let authorization_challenge_endpoint: string | undefined\n    let authorizationServerType: AuthorizationServerType = 'OID4VCI'\n    let authorization_servers: string[] = [issuer]\n    const oid4vciResponse = await MetadataClientV1_0_13.retrieveOpenID4VCIServerMetadata(issuer, { errorOnNotFound: false }) // We will handle errors later, given we will also try other metadata locations\n    let credentialIssuerMetadata = oid4vciResponse?.successBody\n    if (credentialIssuerMetadata) {\n      logger.debug(`Issuer ${issuer} OID4VCI well-known server metadata\\r\\n${JSON.stringify(credentialIssuerMetadata)}`)\n      credential_endpoint = credentialIssuerMetadata.credential_endpoint\n      deferred_credential_endpoint = credentialIssuerMetadata.deferred_credential_endpoint\n      if (credentialIssuerMetadata.token_endpoint) {\n        token_endpoint = credentialIssuerMetadata.token_endpoint\n      }\n      authorization_challenge_endpoint = credentialIssuerMetadata.authorization_challenge_endpoint\n      if (credentialIssuerMetadata.authorization_servers) {\n        authorization_servers = credentialIssuerMetadata.authorization_servers\n      }\n    }\n    // No specific OID4VCI endpoint. Either can be an OAuth2 AS or an OIDC IDP. Let's start with OIDC first\n    // TODO: for now we're taking just the first one\n    let response: OpenIDResponse<AuthorizationServerMetadata> = await retrieveWellknown(\n      authorization_servers[0],\n      WellKnownEndpoints.OPENID_CONFIGURATION,\n      {\n        errorOnNotFound: false,\n      },\n    )\n    let authMetadata = response.successBody\n    if (authMetadata) {\n      logger.debug(`Issuer ${issuer} has OpenID Connect Server metadata in well-known location`)\n      authorizationServerType = 'OIDC'\n    } else {\n      // Now let's do OAuth2\n      // TODO: for now we're taking just the first one\n      response = await retrieveWellknown(authorization_servers[0], WellKnownEndpoints.OAUTH_AS, { errorOnNotFound: false })\n      authMetadata = response.successBody\n    }\n    if (!authMetadata) {\n      // We will always throw an error, no matter whether the user provided the option not to, because this is bad.\n      if (!authorization_servers.includes(issuer)) {\n        throw Error(`Issuer ${issuer} provided a separate authorization server ${authorization_servers}, but that server did not provide metadata`)\n      }\n    } else {\n      if (!authorizationServerType) {\n        authorizationServerType = 'OAuth 2.0'\n      }\n      logger.debug(`Issuer ${issuer} has ${authorizationServerType} Server metadata in well-known location`)\n      if (!authMetadata.authorization_endpoint) {\n        console.warn(\n          `Issuer ${issuer} of type ${authorizationServerType} has no authorization_endpoint! Will use ${authorization_endpoint}. This only works for pre-authorized flows`,\n        )\n      } else if (authorization_endpoint && authMetadata.authorization_endpoint !== authorization_endpoint) {\n        throw Error(\n          `Credential issuer has a different authorization_endpoint (${authorization_endpoint}) from the Authorization Server (${authMetadata.authorization_endpoint})`,\n        )\n      }\n      authorization_endpoint = authMetadata.authorization_endpoint\n      if (authorization_challenge_endpoint && authMetadata.authorization_challenge_endpoint !== authorization_challenge_endpoint) {\n        throw Error(\n          `Credential issuer has a different authorization_challenge_endpoint (${authorization_challenge_endpoint}) from the Authorization Server (${authMetadata.authorization_challenge_endpoint})`,\n        )\n      }\n      authorization_challenge_endpoint = authMetadata.authorization_challenge_endpoint\n      if (!authMetadata.token_endpoint) {\n        throw Error(`Authorization Server ${authorization_servers} did not provide a token_endpoint`)\n      } else if (token_endpoint && authMetadata.token_endpoint !== token_endpoint) {\n        throw Error(\n          `Credential issuer has a different token_endpoint (${token_endpoint}) from the Authorization Server (${authMetadata.token_endpoint})`,\n        )\n      }\n      token_endpoint = authMetadata.token_endpoint\n      if (authMetadata.credential_endpoint) {\n        if (credential_endpoint && authMetadata.credential_endpoint !== credential_endpoint) {\n          logger.debug(\n            `Credential issuer has a different credential_endpoint (${credential_endpoint}) from the Authorization Server (${authMetadata.credential_endpoint}). Will use the issuer value`,\n          )\n        } else {\n          credential_endpoint = authMetadata.credential_endpoint\n        }\n      }\n      if (authMetadata.deferred_credential_endpoint) {\n        if (deferred_credential_endpoint && authMetadata.deferred_credential_endpoint !== deferred_credential_endpoint) {\n          logger.debug(\n            `Credential issuer has a different deferred_credential_endpoint (${deferred_credential_endpoint}) from the Authorization Server (${authMetadata.deferred_credential_endpoint}). Will use the issuer value`,\n          )\n        } else {\n          deferred_credential_endpoint = authMetadata.deferred_credential_endpoint\n        }\n      }\n    }\n\n    if (!authorization_endpoint) {\n      logger.debug(`Issuer ${issuer} does not expose authorization_endpoint, so only pre-auth will be supported`)\n    }\n    if (!token_endpoint) {\n      logger.debug(`Issuer ${issuer} does not have a token_endpoint listed in well-known locations!`)\n      if (opts?.errorOnNotFound) {\n        throw Error(`Could not deduce the token_endpoint for ${issuer}`)\n      } else {\n        token_endpoint = `${issuer}${issuer.endsWith('/') ? 'token' : '/token'}`\n      }\n    }\n    if (!credential_endpoint) {\n      logger.debug(`Issuer ${issuer} does not have a credential_endpoint listed in well-known locations!`)\n      if (opts?.errorOnNotFound) {\n        throw Error(`Could not deduce the credential endpoint for ${issuer}`)\n      } else {\n        credential_endpoint = `${issuer}${issuer.endsWith('/') ? 'credential' : '/credential'}`\n      }\n    }\n\n    if (!credentialIssuerMetadata && authMetadata) {\n      // Apparently everything worked out and the issuer is exposing everything in oAuth2/OIDC well-knowns. Spec is vague about this situation, but we can support it\n      credentialIssuerMetadata = authMetadata as CredentialIssuerMetadataV1_0_13\n    }\n    logger.debug(`Issuer ${issuer} token endpoint ${token_endpoint}, credential endpoint ${credential_endpoint}`)\n    return {\n      issuer,\n      token_endpoint,\n      credential_endpoint,\n      deferred_credential_endpoint,\n      authorization_server: authorization_servers[0],\n      authorization_endpoint,\n      authorization_challenge_endpoint,\n      authorizationServerType,\n      credentialIssuerMetadata: credentialIssuerMetadata,\n      authorizationServerMetadata: authMetadata,\n    }\n  }\n\n  /**\n   * Retrieve only the OID4VCI metadata for the issuer. So no OIDC/OAuth2 metadata\n   *\n   * @param issuerHost The issuer hostname\n   * @param opts\n   */\n  public static async retrieveOpenID4VCIServerMetadata(\n    issuerHost: string,\n    opts?: {\n      errorOnNotFound?: boolean\n    },\n  ): Promise<OpenIDResponse<IssuerMetadataV1_0_13> | undefined> {\n    return retrieveWellknown(issuerHost, WellKnownEndpoints.OPENID4VCI_ISSUER, {\n      errorOnNotFound: opts?.errorOnNotFound === undefined ? true : opts.errorOnNotFound,\n    })\n  }\n}\n","import { assertValidCodeVerifier, CodeChallengeMethod, createCodeChallenge, generateCodeVerifier, PKCEOpts } from '@sphereon/oid4vci-common'\n\nexport const generateMissingPKCEOpts = (pkce: PKCEOpts) => {\n  if (pkce.disabled) {\n    return pkce\n  }\n  if (!pkce.codeChallengeMethod) {\n    pkce.codeChallengeMethod = CodeChallengeMethod.S256\n  }\n  if (!pkce.codeVerifier) {\n    pkce.codeVerifier = generateCodeVerifier()\n  }\n  assertValidCodeVerifier(pkce.codeVerifier)\n  if (!pkce.codeChallenge) {\n    pkce.codeChallenge = createCodeChallenge(pkce.codeVerifier, pkce.codeChallengeMethod)\n  }\n  return pkce\n}\n","import { NotificationErrorResponse, NotificationRequest, NotificationResponseResult, post } from '@sphereon/oid4vci-common'\n\nimport { CredentialRequestOpts } from '../CredentialRequestClient'\nimport { LOG } from '../types'\n\nexport async function sendNotification(\n  credentialRequestOpts: Partial<CredentialRequestOpts>,\n  request: NotificationRequest,\n  accessToken?: string,\n): Promise<NotificationResponseResult> {\n  LOG.info(`Sending status notification event '${request.event}' for id ${request.notification_id}`)\n  if (!credentialRequestOpts.notificationEndpoint) {\n    throw Error(`Cannot send notification when no notification endpoint is provided`)\n  }\n  const token = accessToken ?? credentialRequestOpts.token\n  const response = await post<NotificationErrorResponse>(credentialRequestOpts.notificationEndpoint, JSON.stringify(request), {\n    ...(token && { bearerToken: token }),\n  })\n  const error = response.errorBody?.error !== undefined\n  const result = {\n    error,\n    response: error ? response.errorBody : undefined,\n  }\n  if (error) {\n    LOG.warning(`Notification endpoint returned an error for event '${request.event}' and id ${request.notification_id}: ${response.errorBody}`)\n  } else {\n    LOG.debug(`Notification endpoint returned success for event '${request.event}' and id ${request.notification_id}`)\n  }\n  return result\n}\n","import { VCI_LOGGERS } from '@sphereon/oid4vci-common'\nimport { ISimpleLogger, LogMethod } from '@sphereon/ssi-types'\n\nexport const LOG: ISimpleLogger<string> = VCI_LOGGERS.options('sphereon:oid4vci:client', { methods: [LogMethod.EVENT, LogMethod.DEBUG_PKG] }).get(\n  'sphereon:oid4vci:client',\n)\n","import { getJson, OpenIDResponse, WellKnownEndpoints } from '@sphereon/oid4vci-common'\nimport { Loggers } from '@sphereon/ssi-types'\n\nconst logger = Loggers.DEFAULT.get('sphereon:openid4vci:openid-utils')\n/**\n * Allows to retrieve information from a well-known location\n *\n * @param host The host\n * @param endpointType The endpoint type, currently supports OID4VCI, OIDC and OAuth2 endpoint types\n * @param opts Options, like for instance whether an error should be thrown in case the endpoint doesn't exist\n */\nexport const retrieveWellknown = async <T>(\n  host: string,\n  endpointType: WellKnownEndpoints,\n  opts?: { errorOnNotFound?: boolean },\n): Promise<OpenIDResponse<T>> => {\n  const result: OpenIDResponse<T> = await getJson(`${host.endsWith('/') ? host.slice(0, -1) : host}${endpointType}`, {\n    exceptionOnHttpErrorStatus: opts?.errorOnNotFound,\n  })\n  if (result.origResponse.status >= 400) {\n    // We only get here when error on not found is false\n    logger.debug(`host ${host} with endpoint type ${endpointType} status: ${result.origResponse.status}, ${result.origResponse.statusText}`)\n  }\n  return result\n}\n","import { uuidv4 } from '@sphereon/oid4vc-common'\nimport { AccessTokenRequest, AccessTokenRequestOpts, Jwt, OpenId4VCIVersion } from '@sphereon/oid4vci-common'\n\nimport { ProofOfPossessionBuilder } from '../ProofOfPossessionBuilder'\n\nexport const createJwtBearerClientAssertion = async (\n  request: Partial<AccessTokenRequest>,\n  opts: AccessTokenRequestOpts & {\n    version?: OpenId4VCIVersion\n  },\n): Promise<void> => {\n  const { asOpts, credentialIssuer } = opts\n  if (asOpts?.clientOpts?.clientAssertionType === 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer') {\n    const { clientId = request.client_id, signCallbacks, alg } = asOpts.clientOpts\n    let { kid } = asOpts.clientOpts\n    if (!clientId) {\n      return Promise.reject(Error(`Not client_id supplied, but client-assertion jwt-bearer requested.`))\n    } else if (!kid) {\n      return Promise.reject(Error(`No kid supplied, but client-assertion jwt-bearer requested.`))\n    } else if (typeof signCallbacks?.signCallback !== 'function') {\n      return Promise.reject(Error(`No sign callback supplied, but client-assertion jwt-bearer requested.`))\n    } else if (!credentialIssuer) {\n      return Promise.reject(Error(`No credential issuer supplied, but client-assertion jwt-bearer requested.`))\n    }\n    if (clientId.startsWith('http') && kid.includes('#')) {\n      kid = kid.split('#')[1]\n    }\n    const jwt: Jwt = {\n      header: {\n        typ: 'JWT',\n        kid,\n        alg: alg ?? 'ES256',\n      },\n      payload: {\n        iss: clientId,\n        sub: clientId,\n        aud: credentialIssuer,\n        jti: uuidv4(),\n        exp: Math.floor(Date.now()) / 1000 + 60,\n        iat: Math.floor(Date.now()) / 1000 - 60,\n      },\n    }\n    const pop = await ProofOfPossessionBuilder.fromJwt({\n      jwt,\n      callbacks: signCallbacks,\n      version: opts.version ?? OpenId4VCIVersion.VER_1_0_13,\n      mode: 'JWT',\n    }).build()\n    request.client_assertion_type = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'\n    request.client_assertion = pop.jwt\n  }\n}\n","import { JWK } from '@sphereon/oid4vc-common'\nimport {\n  AccessTokenResponse,\n  Alg,\n  createProofOfPossession,\n  EndpointMetadata,\n  Jwt,\n  NO_JWT_PROVIDED,\n  OpenId4VCIVersion,\n  PoPMode,\n  PROOF_CANT_BE_CONSTRUCTED,\n  ProofOfPossession,\n  ProofOfPossessionCallbacks,\n  Typ,\n} from '@sphereon/oid4vci-common'\n\nexport class ProofOfPossessionBuilder<DIDDoc = never> {\n  private readonly proof?: ProofOfPossession\n  private readonly callbacks?: ProofOfPossessionCallbacks\n  private readonly version: OpenId4VCIVersion\n  private readonly mode: PoPMode = 'pop'\n\n  private kid?: string\n  private jwk?: JWK\n  private aud?: string | string[]\n  private clientId?: string\n  private issuer?: string\n  private jwt?: Jwt\n  private alg?: string\n  private jti?: string\n  private cNonce?: string\n  private typ?: Typ\n\n  private constructor({\n    proof,\n    callbacks,\n    jwt,\n    accessTokenResponse,\n    version,\n    mode = 'pop',\n  }: {\n    proof?: ProofOfPossession\n    callbacks?: ProofOfPossessionCallbacks\n    accessTokenResponse?: AccessTokenResponse\n    jwt?: Jwt\n    version: OpenId4VCIVersion\n    mode?: PoPMode\n  }) {\n    this.mode = mode\n    this.proof = proof\n    this.callbacks = callbacks\n    this.version = version\n    if (jwt) {\n      this.withJwt(jwt)\n    } else {\n      this.withTyp(version < OpenId4VCIVersion.VER_1_0_11 || mode === 'JWT' ? 'JWT' : 'openid4vci-proof+jwt')\n    }\n    if (accessTokenResponse) {\n      this.withAccessTokenResponse(accessTokenResponse)\n    }\n  }\n\n  static manual({\n    jwt,\n    callbacks,\n    version,\n    mode = 'JWT',\n  }: {\n    jwt?: Jwt\n    callbacks: ProofOfPossessionCallbacks\n    version: OpenId4VCIVersion\n    mode?: PoPMode\n  }): ProofOfPossessionBuilder {\n    return new ProofOfPossessionBuilder({ callbacks, jwt, version, mode })\n  }\n\n  static fromJwt({\n    jwt,\n    callbacks,\n    version,\n    mode = 'pop',\n  }: {\n    jwt: Jwt\n    callbacks: ProofOfPossessionCallbacks\n    version: OpenId4VCIVersion\n    mode?: PoPMode\n  }): ProofOfPossessionBuilder {\n    return new ProofOfPossessionBuilder({ callbacks, jwt, version, mode })\n  }\n\n  static fromAccessTokenResponse({\n    accessTokenResponse,\n    callbacks,\n    version,\n    mode = 'pop',\n  }: {\n    accessTokenResponse: AccessTokenResponse\n    callbacks: ProofOfPossessionCallbacks\n    version: OpenId4VCIVersion\n    mode?: PoPMode\n  }): ProofOfPossessionBuilder {\n    return new ProofOfPossessionBuilder({ callbacks, accessTokenResponse, version, mode })\n  }\n\n  static fromProof(proof: ProofOfPossession, version: OpenId4VCIVersion): ProofOfPossessionBuilder {\n    return new ProofOfPossessionBuilder({ proof, version })\n  }\n\n  withAud(aud: string | string[]): this {\n    this.aud = aud\n    return this\n  }\n\n  withClientId(clientId: string): this {\n    this.clientId = clientId\n    return this\n  }\n\n  withKid(kid: string): this {\n    this.kid = kid\n    return this\n  }\n\n  withJWK(jwk: JWK): this {\n    this.jwk = jwk\n    return this\n  }\n\n  withIssuer(issuer: string): this {\n    this.issuer = issuer\n    return this\n  }\n\n  withAlg(alg: Alg | string): this {\n    this.alg = alg\n    return this\n  }\n\n  withJti(jti: string): this {\n    this.jti = jti\n    return this\n  }\n\n  withTyp(typ: Typ): this {\n    if (this.mode === 'pop' && this.version >= OpenId4VCIVersion.VER_1_0_11) {\n      if (!!typ && typ !== 'openid4vci-proof+jwt') {\n        throw Error(`typ must be openid4vci-proof+jwt for version 1.0.11 and up. Provided: ${typ}`)\n      }\n    } else {\n      if (!!typ && typ !== 'JWT') {\n        throw Error(`typ must be jwt for version 1.0.10 and below. Provided: ${typ}`)\n      }\n    }\n    this.typ = typ\n    return this\n  }\n\n  withAccessTokenNonce(cNonce: string): this {\n    this.cNonce = cNonce\n    return this\n  }\n\n  withAccessTokenResponse(accessToken: AccessTokenResponse): this {\n    if (accessToken.c_nonce) {\n      this.withAccessTokenNonce(accessToken.c_nonce)\n    }\n    return this\n  }\n\n  withEndpointMetadata(endpointMetadata: EndpointMetadata): this {\n    this.withIssuer(endpointMetadata.issuer)\n    return this\n  }\n\n  withJwt(jwt: Jwt): this {\n    if (!jwt) {\n      throw new Error(NO_JWT_PROVIDED)\n    }\n    this.jwt = jwt\n    if (!jwt.header) {\n      throw Error(`No JWT header present`)\n    } else if (!jwt.payload) {\n      throw Error(`No JWT payload present`)\n    }\n\n    if (jwt.header.kid) {\n      this.withKid(jwt.header.kid)\n    }\n    if (jwt.header.typ) {\n      this.withTyp(jwt.header.typ as Typ)\n    }\n    if (!this.typ && this.version >= OpenId4VCIVersion.VER_1_0_11) {\n      this.withTyp('openid4vci-proof+jwt')\n    }\n    this.withAlg(jwt.header.alg)\n\n    if (Array.isArray(jwt.payload.aud)) {\n      // Rather do this than take the first value, as it might be very hard to figure out why something is failing\n      throw Error('We cannot handle multiple aud values currently')\n    }\n\n    if (jwt.payload) {\n      if (jwt.payload.iss) this.mode === 'pop' ? this.withClientId(jwt.payload.iss) : this.withIssuer(jwt.payload.iss)\n      if (jwt.payload.aud) this.mode === 'pop' ? this.withIssuer(jwt.payload.aud) : this.withAud(jwt.payload.aud)\n      if (jwt.payload.jti) this.withJti(jwt.payload.jti)\n      if (jwt.payload.nonce) this.withAccessTokenNonce(jwt.payload.nonce)\n    }\n    return this\n  }\n\n  public async build(): Promise<ProofOfPossession> {\n    if (this.proof) {\n      return Promise.resolve(this.proof)\n    } else if (this.callbacks) {\n      return await createProofOfPossession(\n        this.mode,\n        this.callbacks,\n        {\n          typ: this.typ ?? (this.version < OpenId4VCIVersion.VER_1_0_11 || this.mode === 'JWT' ? 'JWT' : 'openid4vci-proof+jwt'),\n          kid: this.kid,\n          jwk: this.jwk,\n          jti: this.jti,\n          alg: this.alg,\n          aud: this.aud,\n          issuer: this.issuer,\n          clientId: this.clientId,\n          ...(this.cNonce && { nonce: this.cNonce }),\n        },\n        this.jwt,\n      )\n    }\n    throw new Error(PROOF_CANT_BE_CONSTRUCTED)\n  }\n}\n","import {\n  decodeJsonProperties,\n  getClientIdFromCredentialOfferPayload,\n  getURIComponentsAsArray,\n  PRE_AUTH_CODE_LITERAL,\n  PRE_AUTH_GRANT_LITERAL,\n  UniformCredentialOfferRequest,\n} from '@sphereon/oid4vci-common'\nimport { fetch } from 'cross-fetch'\n\nexport function isUriEncoded(str: string): boolean {\n  const pattern = /%[0-9A-F]{2}/i\n  return pattern.test(str)\n}\n\nexport async function handleCredentialOfferUri(uri: string) {\n  const uriObj = getURIComponentsAsArray(uri) as unknown as Record<string, string>\n  const credentialOfferUri = decodeURIComponent(uriObj['credential_offer_uri'])\n  const decodedUri = isUriEncoded(credentialOfferUri) ? decodeURIComponent(credentialOfferUri) : credentialOfferUri\n  const response = await fetch(decodedUri)\n\n  if (!(response && response.status >= 200 && response.status < 400)) {\n    return Promise.reject(`the credential offer URI endpoint call was not successful. http code ${response.status} - reason ${response.statusText}`)\n  }\n\n  if (response.headers.get('Content-Type')?.startsWith('application/json') === false) {\n    return Promise.reject('the credential offer URI endpoint did not return content type application/json')\n  }\n\n  return {\n    credential_offer: decodeJsonProperties(await response.json()),\n  }\n}\n\nexport function constructBaseResponse(request: UniformCredentialOfferRequest, scheme: string, baseUrl: string) {\n  const clientId = getClientIdFromCredentialOfferPayload(request.credential_offer)\n  const grants = request.credential_offer?.grants\n\n  return {\n    scheme,\n    baseUrl,\n    ...(clientId && { clientId }),\n    ...request,\n    ...(grants?.authorization_code?.issuer_state && { issuerState: grants.authorization_code.issuer_state }),\n    ...(grants?.[PRE_AUTH_GRANT_LITERAL]?.[PRE_AUTH_CODE_LITERAL] && {\n      preAuthorizedCode: grants[PRE_AUTH_GRANT_LITERAL][PRE_AUTH_CODE_LITERAL],\n    }),\n    ...(request.credential_offer?.grants?.[PRE_AUTH_GRANT_LITERAL]?.tx_code && {\n      txCode: request.credential_offer.grants[PRE_AUTH_GRANT_LITERAL].tx_code,\n    }),\n  }\n}\n","import { dpopTokenRequestNonceError } from '@sphereon/oid4vc-common'\nimport { OpenIDResponse } from '@sphereon/oid4vci-common'\n\nexport type RetryRequestWithDPoPNonce = { ok: true; dpopNonce: string } | { ok: false }\n\nexport function shouldRetryTokenRequestWithDPoPNonce(response: OpenIDResponse<unknown, unknown>): RetryRequestWithDPoPNonce {\n  if (!response.errorBody || response.errorBody.error !== dpopTokenRequestNonceError) {\n    return { ok: false }\n  }\n\n  const dPoPNonce = response.origResponse.headers.get('DPoP-Nonce')\n  if (!dPoPNonce) {\n    throw new Error('Missing required DPoP-Nonce header.')\n  }\n\n  return { ok: true, dpopNonce: dPoPNonce }\n}\n\nexport function shouldRetryResourceRequestWithDPoPNonce(response: OpenIDResponse<unknown, unknown>): RetryRequestWithDPoPNonce {\n  if (!response.errorBody || response.origResponse.status !== 401) {\n    return { ok: false }\n  }\n\n  const wwwAuthenticateHeader = response.origResponse.headers.get('WWW-Authenticate')\n  if (!wwwAuthenticateHeader?.includes(dpopTokenRequestNonceError)) {\n    return { ok: false }\n  }\n\n  const dPoPNonce = response.origResponse.headers.get('DPoP-Nonce')\n  if (!dPoPNonce) {\n    throw new Error('Missing required DPoP-Nonce header.')\n  }\n\n  return { ok: true, dpopNonce: dPoPNonce }\n}\n","import { createDPoP, CreateDPoPClientOpts, getCreateDPoPOptions } from '@sphereon/oid4vc-common'\nimport {\n  AccessTokenRequest,\n  AccessTokenRequestOpts,\n  AccessTokenResponse,\n  assertedUniformCredentialOffer,\n  AuthorizationServerOpts,\n  AuthzFlowType,\n  convertJsonToURI,\n  CredentialOfferV1_0_11,\n  CredentialOfferV1_0_13,\n  DPoPResponseParams,\n  EndpointMetadata,\n  formPost,\n  getIssuerFromCredentialOfferPayload,\n  GrantTypes,\n  IssuerOpts,\n  JsonURIMode,\n  OpenId4VCIVersion,\n  OpenIDResponse,\n  PRE_AUTH_CODE_LITERAL,\n  PRE_AUTH_GRANT_LITERAL,\n  TokenErrorResponse,\n  toUniformCredentialOfferRequest,\n  UniformCredentialOfferPayload,\n} from '@sphereon/oid4vci-common'\nimport { Loggers, ObjectUtils } from '@sphereon/ssi-types'\n\nimport { MetadataClientV1_0_13 } from './MetadataClientV1_0_13'\nimport { createJwtBearerClientAssertion } from './functions'\nimport { shouldRetryTokenRequestWithDPoPNonce } from './functions/dpopUtil'\n\nconst logger = Loggers.DEFAULT.get('sphereon:oid4vci:token')\n\nexport class AccessTokenClientV1_0_11 {\n  public async acquireAccessToken(opts: AccessTokenRequestOpts): Promise<OpenIDResponse<AccessTokenResponse, DPoPResponseParams>> {\n    const { asOpts, pin, codeVerifier, code, redirectUri, metadata, createDPoPOpts } = opts\n\n    const credentialOffer = opts.credentialOffer ? await assertedUniformCredentialOffer(opts.credentialOffer) : undefined\n    const isPinRequired = credentialOffer && this.isPinRequiredValue(credentialOffer.credential_offer)\n    const issuer =\n      opts.credentialIssuer ??\n      (credentialOffer ? getIssuerFromCredentialOfferPayload(credentialOffer.credential_offer) : (metadata?.issuer as string))\n    if (!issuer) {\n      throw Error('Issuer required at this point')\n    }\n    const issuerOpts = {\n      issuer,\n    }\n\n    return await this.acquireAccessTokenUsingRequest({\n      accessTokenRequest: await this.createAccessTokenRequest({\n        credentialOffer,\n        asOpts,\n        codeVerifier,\n        code,\n        redirectUri,\n        pin,\n        credentialIssuer: issuer,\n        metadata,\n        additionalParams: opts.additionalParams,\n        pinMetadata: opts.pinMetadata,\n      }),\n      isPinRequired,\n      metadata,\n      asOpts,\n      issuerOpts,\n      createDPoPOpts,\n    })\n  }\n\n  public async acquireAccessTokenUsingRequest({\n    accessTokenRequest,\n    isPinRequired,\n    metadata,\n    asOpts,\n    createDPoPOpts,\n    issuerOpts,\n  }: {\n    accessTokenRequest: AccessTokenRequest\n    isPinRequired?: boolean\n    metadata?: EndpointMetadata\n    asOpts?: AuthorizationServerOpts\n    issuerOpts?: IssuerOpts\n    createDPoPOpts?: CreateDPoPClientOpts\n  }): Promise<OpenIDResponse<AccessTokenResponse, DPoPResponseParams>> {\n    this.validate(accessTokenRequest, isPinRequired)\n\n    const requestTokenURL = AccessTokenClientV1_0_11.determineTokenURL({\n      asOpts,\n      issuerOpts,\n      metadata: metadata\n        ? metadata\n        : issuerOpts?.fetchMetadata\n          ? await MetadataClientV1_0_13.retrieveAllMetadata(issuerOpts.issuer, { errorOnNotFound: false })\n          : undefined,\n    })\n\n    const useDpop = createDPoPOpts?.dPoPSigningAlgValuesSupported && createDPoPOpts.dPoPSigningAlgValuesSupported.length > 0\n    let dPoP = useDpop ? await createDPoP(getCreateDPoPOptions(createDPoPOpts, requestTokenURL)) : undefined\n\n    let response = await this.sendAuthCode(requestTokenURL, accessTokenRequest, dPoP ? { headers: { dpop: dPoP } } : undefined)\n\n    let nextDPoPNonce = createDPoPOpts?.jwtPayloadProps.nonce\n    const retryWithNonce = shouldRetryTokenRequestWithDPoPNonce(response)\n    if (retryWithNonce.ok && createDPoPOpts) {\n      createDPoPOpts.jwtPayloadProps.nonce = retryWithNonce.dpopNonce\n\n      dPoP = await createDPoP(getCreateDPoPOptions(createDPoPOpts, requestTokenURL))\n      response = await this.sendAuthCode(requestTokenURL, accessTokenRequest, dPoP ? { headers: { dpop: dPoP } } : undefined)\n      const successDPoPNonce = response.origResponse.headers.get('DPoP-Nonce')\n\n      nextDPoPNonce = successDPoPNonce ?? retryWithNonce.dpopNonce\n    }\n\n    if (response.successBody && createDPoPOpts && response.successBody.token_type !== 'DPoP') {\n      throw new Error('Invalid token type returned. Expected DPoP. Received: ' + response.successBody.token_type)\n    }\n\n    return {\n      ...response,\n      ...(nextDPoPNonce && { params: { dpop: { dpopNonce: nextDPoPNonce } } }),\n    }\n  }\n\n  public async createAccessTokenRequest(opts: Omit<AccessTokenRequestOpts, 'createDPoPOpts'>): Promise<AccessTokenRequest> {\n    const { asOpts, pin, codeVerifier, code, redirectUri } = opts\n    const credentialOfferRequest = opts.credentialOffer\n      ? await toUniformCredentialOfferRequest(opts.credentialOffer as CredentialOfferV1_0_11 | CredentialOfferV1_0_13)\n      : undefined\n    const request: Partial<AccessTokenRequest> = { ...opts.additionalParams }\n    const credentialIssuer = opts.credentialIssuer ?? credentialOfferRequest?.credential_offer?.credential_issuer ?? opts.metadata?.issuer\n\n    if (asOpts?.clientOpts?.clientId) {\n      request.client_id = asOpts.clientOpts.clientId\n    }\n    await createJwtBearerClientAssertion(request, { ...opts, version: OpenId4VCIVersion.VER_1_0_11, credentialIssuer })\n\n    // Prefer AUTHORIZATION_CODE over PRE_AUTHORIZED_CODE_FLOW\n    if (!credentialOfferRequest || credentialOfferRequest.supportedFlows.includes(AuthzFlowType.AUTHORIZATION_CODE_FLOW)) {\n      request.grant_type = GrantTypes.AUTHORIZATION_CODE\n      request.code = code\n      request.redirect_uri = redirectUri\n\n      if (codeVerifier) {\n        request.code_verifier = codeVerifier\n      }\n\n      return request as AccessTokenRequest\n    }\n\n    if (credentialOfferRequest?.supportedFlows.includes(AuthzFlowType.PRE_AUTHORIZED_CODE_FLOW)) {\n      this.assertNumericPin(this.isPinRequiredValue(credentialOfferRequest.credential_offer), pin)\n      request.user_pin = pin\n\n      request.grant_type = GrantTypes.PRE_AUTHORIZED_CODE\n      // we actually know it is there because of the isPreAuthCode call\n      request[PRE_AUTH_CODE_LITERAL] = credentialOfferRequest?.credential_offer.grants?.[PRE_AUTH_GRANT_LITERAL]?.[PRE_AUTH_CODE_LITERAL]\n\n      return request as AccessTokenRequest\n    }\n    throw new Error('Credential offer request does not follow neither pre-authorized code nor authorization code flow requirements.')\n  }\n\n  private assertPreAuthorizedGrantType(grantType: GrantTypes): void {\n    if (GrantTypes.PRE_AUTHORIZED_CODE !== grantType) {\n      throw new Error('grant type must be PRE_AUTH_GRANT_LITERAL')\n    }\n  }\n\n  private assertAuthorizationGrantType(grantType: GrantTypes): void {\n    if (GrantTypes.AUTHORIZATION_CODE !== grantType) {\n      throw new Error(\"grant type must be 'authorization_code'\")\n    }\n  }\n\n  private isPinRequiredValue(requestPayload: UniformCredentialOfferPayload): boolean {\n    let isPinRequired = false\n    if (!requestPayload) {\n      throw new Error(TokenErrorResponse.invalid_request)\n    }\n    const issuer = getIssuerFromCredentialOfferPayload(requestPayload)\n    if (requestPayload.grants?.[PRE_AUTH_GRANT_LITERAL]) {\n      isPinRequired = requestPayload.grants[PRE_AUTH_GRANT_LITERAL]?.user_pin_required ?? false\n    }\n    logger.debug(`Pin required for issuer ${issuer}: ${isPinRequired}`)\n    return isPinRequired\n  }\n\n  private assertNumericPin(isPinRequired?: boolean, pin?: string): void {\n    if (isPinRequired) {\n      if (!pin || !/^\\d{1,8}$/.test(pin)) {\n        logger.debug(`Pin is not 1 to 8 digits long`)\n        throw new Error('A valid pin consisting of maximal 8 numeric characters must be present.')\n      }\n    } else if (pin) {\n      logger.debug(`Pin set, whilst not required`)\n      throw new Error('Cannot set a pin, when the pin is not required.')\n    }\n  }\n\n  private assertNonEmptyPreAuthorizedCode(accessTokenRequest: AccessTokenRequest): void {\n    if (!accessTokenRequest[PRE_AUTH_CODE_LITERAL]) {\n      logger.debug(`No pre-authorized code present, whilst it is required`)\n      throw new Error('Pre-authorization must be proven by presenting the pre-authorized code. Code must be present.')\n    }\n  }\n\n  private assertNonEmptyCodeVerifier(accessTokenRequest: AccessTokenRequest): void {\n    if (!accessTokenRequest.code_verifier) {\n      logger.debug('No code_verifier present, whilst it is required')\n      throw new Error('Authorization flow requires the code_verifier to be present')\n    }\n  }\n\n  private assertNonEmptyCode(accessTokenRequest: AccessTokenRequest): void {\n    if (!accessTokenRequest.code) {\n      logger.debug('No code present, whilst it is required')\n      throw new Error('Authorization flow requires the code to be present')\n    }\n  }\n\n  private validate(accessTokenRequest: AccessTokenRequest, isPinRequired?: boolean): void {\n    if (accessTokenRequest.grant_type === GrantTypes.PRE_AUTHORIZED_CODE) {\n      this.assertPreAuthorizedGrantType(accessTokenRequest.grant_type)\n      this.assertNonEmptyPreAuthorizedCode(accessTokenRequest)\n      this.assertNumericPin(isPinRequired, accessTokenRequest.user_pin)\n    } else if (accessTokenRequest.grant_type === GrantTypes.AUTHORIZATION_CODE) {\n      this.assertAuthorizationGrantType(accessTokenRequest.grant_type)\n      this.assertNonEmptyCodeVerifier(accessTokenRequest)\n      this.assertNonEmptyCode(accessTokenRequest)\n    } else {\n      this.throwNotSupportedFlow()\n    }\n  }\n\n  private async sendAuthCode(\n    requestTokenURL: string,\n    accessTokenRequest: AccessTokenRequest,\n    opts?: { headers?: Record<string, string> },\n  ): Promise<OpenIDResponse<AccessTokenResponse>> {\n    return await formPost(requestTokenURL, convertJsonToURI(accessTokenRequest, { mode: JsonURIMode.X_FORM_WWW_URLENCODED }), {\n      customHeaders: opts?.headers ? opts.headers : undefined,\n    })\n  }\n\n  public static determineTokenURL({\n    asOpts,\n    issuerOpts,\n    metadata,\n  }: {\n    asOpts?: AuthorizationServerOpts\n    issuerOpts?: IssuerOpts\n    metadata?: EndpointMetadata\n  }): string {\n    if (!asOpts && !metadata?.token_endpoint && !issuerOpts) {\n      throw new Error('Cannot determine token URL if no issuer, metadata and no Authorization Server values are present')\n    }\n    let url\n    if (asOpts && asOpts.as) {\n      url = this.creatTokenURLFromURL(asOpts.as, asOpts?.allowInsecureEndpoints, asOpts.tokenEndpoint)\n    } else if (metadata?.token_endpoint) {\n      url = metadata.token_endpoint\n    } else {\n      if (!issuerOpts?.issuer) {\n        throw Error('Either authorization server options, a token endpoint or issuer options are required at this point')\n      }\n      url = this.creatTokenURLFromURL(issuerOpts.issuer, asOpts?.allowInsecureEndpoints, issuerOpts.tokenEndpoint)\n    }\n\n    if (!url || !ObjectUtils.isString(url)) {\n      throw new Error('No authorization server token URL present. Cannot acquire access token')\n    }\n    logger.debug(`Token endpoint determined to be ${url}`)\n    return url\n  }\n\n  private static creatTokenURLFromURL(url: string, allowInsecureEndpoints?: boolean, tokenEndpoint?: string): string {\n    if (allowInsecureEndpoints !== true && url.startsWith('http:')) {\n      throw Error(\n        `Unprotected token endpoints are not allowed ${url}. Use the 'allowInsecureEndpoints' param if you really need this for dev/testing!`,\n      )\n    }\n    const hostname = url.replace(/https?:\\/\\//, '').replace(/\\/$/, '')\n    const endpoint = tokenEndpoint ? (tokenEndpoint.startsWith('/') ? tokenEndpoint : tokenEndpoint.substring(1)) : '/token'\n    const scheme = url.split('://')[0]\n    return `${scheme ? scheme + '://' : 'https://'}${hostname}${endpoint}`\n  }\n\n  private throwNotSupportedFlow(): void {\n    logger.debug(`Only pre-authorized or authorization code flows supported.`)\n    throw new Error('Only pre-authorized-code or authorization code flows are supported')\n  }\n}\n","import {\n  AuthorizationChallengeCodeResponse,\n  AuthorizationChallengeRequestOpts,\n  AuthorizationDetails,\n  AuthorizationRequestOpts,\n  CodeChallengeMethod,\n  CommonAuthorizationChallengeRequest,\n  convertJsonToURI,\n  CreateRequestObjectMode,\n  CredentialConfigurationSupportedV1_0_13,\n  CredentialDefinitionJwtVcJsonLdAndLdpVcV1_0_13,\n  CredentialDefinitionJwtVcJsonV1_0_13,\n  CredentialOfferPayloadV1_0_13,\n  CredentialOfferRequestWithBaseUrl,\n  determineSpecVersionFromOffer,\n  EndpointMetadata,\n  EndpointMetadataResultV1_0_13,\n  formPost,\n  IssuerOpts,\n  isW3cCredentialSupported,\n  JsonURIMode,\n  Jwt,\n  OpenId4VCIVersion,\n  OpenIDResponse,\n  PARMode,\n  PKCEOpts,\n  PushedAuthorizationResponse,\n  RequestObjectOpts,\n  ResponseType,\n} from '@sphereon/oid4vci-common'\nimport { Loggers } from '@sphereon/ssi-types'\n\nimport { MetadataClient } from './MetadataClient'\nimport { ProofOfPossessionBuilder } from './ProofOfPossessionBuilder'\n\nconst logger = Loggers.DEFAULT.get('sphereon:oid4vci')\n\nexport async function createSignedAuthRequestWhenNeeded(requestObject: Record<string, any>, opts: RequestObjectOpts & { aud?: string }) {\n  if (opts.requestObjectMode === CreateRequestObjectMode.REQUEST_URI) {\n    throw Error(`Request Object Mode ${opts.requestObjectMode} is not supported yet`)\n  } else if (opts.requestObjectMode === CreateRequestObjectMode.REQUEST_OBJECT) {\n    if (typeof opts.signCallbacks?.signCallback !== 'function') {\n      throw Error(`No request object sign callback found, whilst request object mode was set to ${opts.requestObjectMode}`)\n    } else if (!opts.kid) {\n      throw Error(`No kid found, whilst request object mode was set to ${opts.requestObjectMode}`)\n    }\n    let client_metadata: any\n    if (opts.clientMetadata || opts.jwksUri) {\n      client_metadata = opts.clientMetadata ?? {}\n      if (opts.jwksUri) {\n        client_metadata['jwks_uri'] = opts.jwksUri\n      }\n    }\n    let authorization_details = requestObject['authorization_details']\n    if (typeof authorization_details === 'string') {\n      authorization_details = JSON.parse(requestObject.authorization_details)\n    }\n    if (!requestObject.aud && opts.aud) {\n      requestObject.aud = opts.aud\n    }\n    const iss = requestObject.iss ?? opts.iss ?? requestObject.client_id\n\n    const jwt: Jwt = {\n      header: { alg: 'ES256', kid: opts.kid, typ: 'JWT' },\n      payload: { ...requestObject, iss, authorization_details, ...(client_metadata && { client_metadata }) },\n    }\n    const pop = await ProofOfPossessionBuilder.fromJwt({\n      jwt,\n      callbacks: opts.signCallbacks,\n      version: OpenId4VCIVersion.VER_1_0_11,\n      mode: 'JWT',\n    }).build()\n    requestObject['request'] = pop.jwt\n  }\n}\n\nfunction filterSupportedCredentials(\n  credentialOffer: CredentialOfferPayloadV1_0_13,\n  credentialsSupported?: Record<string, CredentialConfigurationSupportedV1_0_13>,\n): (CredentialConfigurationSupportedV1_0_13 & { configuration_id: string })[] {\n  if (!credentialOffer.credential_configuration_ids || !credentialsSupported) {\n    return []\n  }\n  return Object.entries(credentialsSupported)\n    .filter((entry) => credentialOffer.credential_configuration_ids?.includes(entry[0]))\n    .map((entry) => {\n      return { ...entry[1], configuration_id: entry[0] }\n    })\n}\n\nexport const createAuthorizationRequestUrl = async ({\n  pkce,\n  endpointMetadata,\n  authorizationRequest,\n  credentialOffer,\n  credentialConfigurationSupported,\n  clientId,\n  version,\n}: {\n  pkce: PKCEOpts\n  endpointMetadata: EndpointMetadataResultV1_0_13\n  authorizationRequest: AuthorizationRequestOpts\n  credentialOffer?: CredentialOfferRequestWithBaseUrl\n  credentialConfigurationSupported?: Record<string, CredentialConfigurationSupportedV1_0_13>\n  clientId?: string\n  version?: OpenId4VCIVersion\n}): Promise<string> => {\n  function removeDisplayAndValueTypes(obj: any) {\n    const newObj = { ...obj }\n    for (const prop in newObj) {\n      if (['display', 'value_type'].includes(prop)) {\n        delete newObj[prop]\n      } else if (typeof newObj[prop] === 'object') {\n        newObj[prop] = removeDisplayAndValueTypes(newObj[prop])\n      }\n    }\n\n    return newObj\n  }\n\n  const { redirectUri, requestObjectOpts = { requestObjectMode: CreateRequestObjectMode.NONE } } = authorizationRequest\n  const client_id = clientId ?? authorizationRequest.clientId\n\n  // Authorization server metadata takes precedence\n  const authorizationMetadata = endpointMetadata.authorizationServerMetadata ?? endpointMetadata.credentialIssuerMetadata\n\n  let { authorizationDetails } = authorizationRequest\n  const parMode = authorizationMetadata?.require_pushed_authorization_requests\n    ? PARMode.REQUIRE\n    : (authorizationRequest.parMode ?? (client_id ? PARMode.AUTO : PARMode.NEVER))\n  // Scope and authorization_details can be used in the same authorization request\n  // https://datatracker.ietf.org/doc/html/draft-ietf-oauth-rar-23#name-relationship-to-scope-param\n  if (!authorizationRequest.scope && !authorizationDetails) {\n    if (!credentialOffer) {\n      throw Error('Please provide a scope or authorization_details if no credential offer is present')\n    }\n    if ('credentials' in credentialOffer.credential_offer) {\n      throw new Error('CredentialOffer format is wrong.')\n    }\n    const ver = version ?? determineSpecVersionFromOffer(credentialOffer.credential_offer) ?? OpenId4VCIVersion.VER_1_0_13\n    const creds =\n      ver === OpenId4VCIVersion.VER_1_0_13\n        ? filterSupportedCredentials(credentialOffer.credential_offer as CredentialOfferPayloadV1_0_13, credentialConfigurationSupported)\n        : []\n\n    authorizationDetails = creds.flatMap((cred) => {\n      const locations = [credentialOffer?.credential_offer.credential_issuer ?? endpointMetadata.issuer]\n\n      // TODO: credential_configuration_id seems to always be defined?\n      const credential_configuration_id: string | undefined = cred.configuration_id\n      const format = credential_configuration_id ? undefined : cred.format\n\n      if (!credential_configuration_id && !cred.format) {\n        throw Error('format is required in authorization details')\n      }\n\n      // SD-JWT VC\n      const vct = cred.format === 'vc+sd-jwt' ? cred.vct : undefined\n      const doctype = cred.format === 'mso_mdoc' ? cred.doctype : undefined\n\n      // W3C credentials have a credential definition, the rest does not\n      let credential_definition: undefined | Partial<CredentialDefinitionJwtVcJsonV1_0_13 | CredentialDefinitionJwtVcJsonLdAndLdpVcV1_0_13> =\n        undefined\n      if (isW3cCredentialSupported(cred)) {\n        credential_definition = {\n          ...cred.credential_definition,\n          // type: OPTIONAL. Array as defined in Appendix A.1.1.2. This claim contains the type values the Wallet requests authorization for at the Credential Issuer. It MUST be present if the claim format is present in the root of the authorization details object. It MUST not be present otherwise.\n          // It meens we have a config_id, already mapping it to an explicit format and types\n          type: format ? cred.credential_definition.type : undefined,\n          credentialSubject: cred.credential_definition.credentialSubject\n            ? removeDisplayAndValueTypes(cred.credential_definition.credentialSubject)\n            : undefined,\n        }\n      }\n\n      return {\n        type: 'openid_credential',\n        locations,\n        ...(credential_definition && { credential_definition }),\n        ...(credential_configuration_id && { credential_configuration_id }),\n        ...(format && { format }),\n        ...(vct && { vct, claims: cred.claims ? removeDisplayAndValueTypes(cred.claims) : undefined }),\n        ...(doctype && { doctype, claims: cred.claims ? removeDisplayAndValueTypes(cred.claims) : undefined }),\n      } as AuthorizationDetails\n    })\n    if (!authorizationDetails || authorizationDetails.length === 0) {\n      throw Error(`Could not create authorization details from credential offer. Please pass in explicit details`)\n    }\n  }\n  if (!endpointMetadata?.authorization_endpoint) {\n    throw Error('Server metadata does not contain authorization endpoint')\n  }\n  const parEndpoint = authorizationMetadata?.pushed_authorization_request_endpoint\n\n  let queryObj: Record<string, any> | PushedAuthorizationResponse = {\n    response_type: ResponseType.AUTH_CODE,\n    ...(!pkce.disabled && {\n      code_challenge_method: pkce.codeChallengeMethod ?? CodeChallengeMethod.S256,\n      code_challenge: pkce.codeChallenge,\n    }),\n    authorization_details: JSON.stringify(handleAuthorizationDetails(endpointMetadata, authorizationDetails)),\n    ...(redirectUri && { redirect_uri: redirectUri }),\n    ...(client_id && { client_id }),\n\n    ...(credentialOffer?.issuerState && {\n      issuer_state: credentialOffer.issuerState,\n    }),\n    scope: authorizationRequest.scope,\n  }\n\n  if (credentialOffer?.issuerState) {\n    /* We also pass it in as state, as this would allow an external AS without integration to return it back to the wallet */\n    queryObj.state = credentialOffer?.issuerState\n  }\n\n  if (!parEndpoint && parMode === PARMode.REQUIRE) {\n    throw Error(`PAR mode is set to required by Authorization Server does not support PAR!`)\n  } else if (parEndpoint && parMode !== PARMode.NEVER) {\n    logger.debug(`USING PAR with endpoint ${parEndpoint}`)\n\n    const parResponse = await formPost<PushedAuthorizationResponse>(\n      parEndpoint,\n      convertJsonToURI(queryObj, {\n        mode: JsonURIMode.X_FORM_WWW_URLENCODED,\n        uriTypeProperties: ['client_id', 'request_uri', 'redirect_uri', 'scope', 'authorization_details', 'issuer_state', 'state'],\n      }),\n      { contentType: 'application/x-www-form-urlencoded', accept: 'application/json' },\n    )\n    if (parResponse.errorBody || !parResponse.successBody) {\n      if (parMode === PARMode.REQUIRE) {\n        throw Error(`PAR error: ${parResponse.origResponse.statusText}`)\n      }\n\n      logger.debug('Falling back to regular request URI, since PAR failed', JSON.stringify(parResponse.errorBody))\n    } else {\n      logger.debug(`PAR response: ${JSON.stringify(parResponse.successBody, null, 2)}`)\n      queryObj = { /*response_type: ResponseType.AUTH_CODE,*/ client_id, request_uri: parResponse.successBody.request_uri }\n    }\n  }\n  await createSignedAuthRequestWhenNeeded(queryObj, { ...requestObjectOpts, aud: endpointMetadata.authorization_server })\n\n  logger.debug(`Object that will become query params: ` + JSON.stringify(queryObj, null, 2))\n  const url = convertJsonToURI(queryObj, {\n    baseUrl: endpointMetadata.authorization_endpoint,\n    uriTypeProperties: ['client_id', 'request_uri', 'redirect_uri', 'scope', 'authorization_details', 'issuer_state', 'state'],\n    // arrayTypeProperties: ['authorization_details'],\n    mode: JsonURIMode.X_FORM_WWW_URLENCODED,\n    // We do not add the version here, as this always needs to be form encoded\n  })\n  logger.debug(`Authorization Request URL: ${url}`)\n  return url\n}\n\nconst handleAuthorizationDetails = (\n  endpointMetadata: EndpointMetadataResultV1_0_13,\n  authorizationDetails?: AuthorizationDetails | AuthorizationDetails[],\n): AuthorizationDetails | AuthorizationDetails[] | undefined => {\n  if (authorizationDetails) {\n    if (typeof authorizationDetails === 'string') {\n      // backwards compat for older versions of the lib\n      return authorizationDetails\n    }\n    if (Array.isArray(authorizationDetails)) {\n      return authorizationDetails\n        .filter((value) => typeof value !== 'string')\n        .map((value) => handleLocations(endpointMetadata, typeof value === 'string' ? value : { ...value }))\n    } else {\n      return handleLocations(endpointMetadata, { ...authorizationDetails })\n    }\n  }\n  return authorizationDetails\n}\n\nconst handleLocations = (endpointMetadata: EndpointMetadataResultV1_0_13, authorizationDetails: AuthorizationDetails) => {\n  if (typeof authorizationDetails === 'string') {\n    // backwards compat for older versions of the lib\n    return authorizationDetails\n  }\n  if (authorizationDetails && (endpointMetadata.credentialIssuerMetadata?.authorization_server || endpointMetadata.authorization_endpoint)) {\n    if (authorizationDetails.locations) {\n      if (Array.isArray(authorizationDetails.locations)) {\n        authorizationDetails.locations.push(endpointMetadata.issuer)\n      } else {\n        authorizationDetails.locations = [authorizationDetails.locations as string, endpointMetadata.issuer]\n      }\n    } else {\n      authorizationDetails.locations = [endpointMetadata.issuer]\n    }\n  }\n  return authorizationDetails\n}\n\nexport const acquireAuthorizationChallengeAuthCode = async (\n  opts: AuthorizationChallengeRequestOpts,\n): Promise<OpenIDResponse<AuthorizationChallengeCodeResponse>> => {\n  const { metadata } = opts\n\n  const issuer = opts.credentialIssuer ?? (opts?.metadata?.issuer as string)\n  if (!issuer) {\n    throw Error('Issuer required at this point')\n  }\n\n  const issuerOpts = {\n    issuer,\n  }\n\n  return await acquireAuthorizationChallengeAuthCodeUsingRequest({\n    authorizationChallengeRequest: await createAuthorizationChallengeRequest(opts),\n    metadata,\n    issuerOpts,\n  })\n}\n\nexport const acquireAuthorizationChallengeAuthCodeUsingRequest = async (opts: {\n  authorizationChallengeRequest: CommonAuthorizationChallengeRequest\n  metadata?: EndpointMetadata\n  issuerOpts?: IssuerOpts\n}): Promise<OpenIDResponse<AuthorizationChallengeCodeResponse>> => {\n  const { authorizationChallengeRequest, issuerOpts } = opts\n  const metadata = opts?.metadata\n    ? opts?.metadata\n    : issuerOpts?.fetchMetadata\n      ? await MetadataClient.retrieveAllMetadata(issuerOpts.issuer, { errorOnNotFound: false })\n      : undefined\n  const authorizationChallengeCodeUrl = metadata?.authorization_challenge_endpoint\n\n  if (!authorizationChallengeCodeUrl) {\n    return Promise.reject(Error('Cannot determine authorization challenge endpoint URL'))\n  }\n\n  const response = await sendAuthorizationChallengeRequest(authorizationChallengeCodeUrl, authorizationChallengeRequest)\n\n  return response\n}\n\nexport const createAuthorizationChallengeRequest = async (opts: AuthorizationChallengeRequestOpts): Promise<CommonAuthorizationChallengeRequest> => {\n  const { clientId, issuerState, authSession, scope, codeChallenge, codeChallengeMethod, presentationDuringIssuanceSession } = opts\n\n  const request: CommonAuthorizationChallengeRequest = {\n    client_id: clientId,\n    issuer_state: issuerState,\n    auth_session: authSession,\n    scope,\n    code_challenge: codeChallenge,\n    code_challenge_method: codeChallengeMethod,\n    presentation_during_issuance_session: presentationDuringIssuanceSession,\n  }\n\n  return request\n}\n\nexport const sendAuthorizationChallengeRequest = async (\n  authorizationChallengeCodeUrl: string,\n  authorizationChallengeRequest: CommonAuthorizationChallengeRequest,\n  opts?: { headers?: Record<string, string> },\n): Promise<OpenIDResponse<AuthorizationChallengeCodeResponse>> => {\n  return await formPost(authorizationChallengeCodeUrl, convertJsonToURI(authorizationChallengeRequest, { mode: JsonURIMode.X_FORM_WWW_URLENCODED }), {\n    customHeaders: opts?.headers ? opts.headers : undefined,\n  })\n}\n","import {\n  AuthorizationServerMetadata,\n  AuthorizationServerType,\n  CredentialIssuerMetadataV1_0_11,\n  CredentialIssuerMetadataV1_0_13,\n  CredentialOfferPayload,\n  CredentialOfferPayloadV1_0_13,\n  CredentialOfferRequestWithBaseUrl,\n  determineSpecVersionFromOffer,\n  EndpointMetadataResultV1_0_11,\n  EndpointMetadataResultV1_0_13,\n  getIssuerFromCredentialOfferPayload,\n  IssuerMetadataV1_0_08,\n  OpenId4VCIVersion,\n  OpenIDResponse,\n  WellKnownEndpoints,\n} from '@sphereon/oid4vci-common'\nimport { Loggers } from '@sphereon/ssi-types'\n\nimport { MetadataClientV1_0_11 } from './MetadataClientV1_0_11'\nimport { MetadataClientV1_0_13 } from './MetadataClientV1_0_13'\nimport { retrieveWellknown } from './functions'\n\nconst logger = Loggers.DEFAULT.get('sphereon:oid4vci:metadata')\n\nexport class MetadataClient {\n  /**\n   * Retrieve metadata using the Initiation obtained from a previous step\n   *\n   * @param credentialOffer\n   */\n  public static async retrieveAllMetadataFromCredentialOffer(\n    credentialOffer: CredentialOfferRequestWithBaseUrl,\n  ): Promise<EndpointMetadataResultV1_0_13 | EndpointMetadataResultV1_0_11> {\n    if (determineSpecVersionFromOffer(credentialOffer.credential_offer) >= OpenId4VCIVersion.VER_1_0_13) {\n      return await MetadataClientV1_0_13.retrieveAllMetadataFromCredentialOffer(credentialOffer)\n    } else {\n      return await MetadataClientV1_0_11.retrieveAllMetadataFromCredentialOffer(credentialOffer)\n    }\n  }\n\n  /**\n   * Retrieve the metada using the initiation request obtained from a previous step\n   * @param request\n   */\n  public static async retrieveAllMetadataFromCredentialOfferRequest(\n    request: CredentialOfferPayload,\n  ): Promise<EndpointMetadataResultV1_0_13 | EndpointMetadataResultV1_0_11> {\n    const issuer = getIssuerFromCredentialOfferPayload(request)\n    if (issuer) {\n      if (determineSpecVersionFromOffer(request) >= OpenId4VCIVersion.VER_1_0_13) {\n        return MetadataClientV1_0_13.retrieveAllMetadataFromCredentialOfferRequest(request as CredentialOfferPayloadV1_0_13)\n      } else {\n        return MetadataClientV1_0_11.retrieveAllMetadataFromCredentialOfferRequest(request)\n      }\n    }\n    throw new Error(\"can't retrieve metadata from CredentialOfferRequest. No issuer field is present\")\n  }\n\n  /**\n   * Retrieve all metadata from an issuer\n   * @param issuer The issuer URL\n   * @param opts\n   */\n  public static async retrieveAllMetadata(\n    issuer: string,\n    opts?: { errorOnNotFound: boolean },\n  ): Promise<EndpointMetadataResultV1_0_13 | EndpointMetadataResultV1_0_11> {\n    let token_endpoint: string | undefined\n    let credential_endpoint: string | undefined\n    let deferred_credential_endpoint: string | undefined\n    let authorization_endpoint: string | undefined\n    let authorization_challenge_endpoint: string | undefined\n    let authorizationServerType: AuthorizationServerType = 'OID4VCI'\n    let authorization_servers: string[] | undefined = [issuer]\n    let authorization_server: string | undefined = undefined\n    const oid4vciResponse = await MetadataClient.retrieveOpenID4VCIServerMetadata(issuer, { errorOnNotFound: false }) // We will handle errors later, given we will also try other metadata locations\n    let credentialIssuerMetadata = oid4vciResponse?.successBody\n    if (credentialIssuerMetadata) {\n      logger.debug(`Issuer ${issuer} OID4VCI well-known server metadata\\r\\n${JSON.stringify(credentialIssuerMetadata)}`)\n      credential_endpoint = credentialIssuerMetadata.credential_endpoint\n      deferred_credential_endpoint = credentialIssuerMetadata.deferred_credential_endpoint\n        ? (credentialIssuerMetadata.deferred_credential_endpoint as string)\n        : undefined\n      if (credentialIssuerMetadata.token_endpoint) {\n        token_endpoint = credentialIssuerMetadata.token_endpoint\n      }\n      authorization_challenge_endpoint = credentialIssuerMetadata.authorization_challenge_endpoint\n      if (credentialIssuerMetadata.authorization_servers) {\n        authorization_servers = credentialIssuerMetadata.authorization_servers as string[]\n      } else if (credentialIssuerMetadata.authorization_server) {\n        authorization_server = credentialIssuerMetadata.authorization_server as string\n        authorization_servers = [authorization_server]\n      }\n    }\n    // No specific OID4VCI endpoint. Either can be an OAuth2 AS or an OIDC IDP. Let's start with OIDC first\n    // TODO: for now we're taking just the first one\n    let response: OpenIDResponse<AuthorizationServerMetadata> = await retrieveWellknown(\n      authorization_servers[0],\n      WellKnownEndpoints.OPENID_CONFIGURATION,\n      {\n        errorOnNotFound: false,\n      },\n    )\n    let authMetadata = response.successBody\n    if (authMetadata) {\n      logger.debug(`Issuer ${issuer} has OpenID Connect Server metadata in well-known location`)\n      authorizationServerType = 'OIDC'\n    } else {\n      // Now let's do OAuth2\n      // TODO: for now we're taking just the first one\n      response = await retrieveWellknown(authorization_servers[0], WellKnownEndpoints.OAUTH_AS, { errorOnNotFound: false })\n      authMetadata = response.successBody\n    }\n    if (!authMetadata) {\n      // We will always throw an error, no matter whether the user provided the option not to, because this is bad.\n      if (!authorization_servers.includes(issuer)) {\n        throw Error(`Issuer ${issuer} provided a separate authorization server ${authorization_servers}, but that server did not provide metadata`)\n      }\n    } else {\n      if (!authorizationServerType) {\n        authorizationServerType = 'OAuth 2.0'\n      }\n      logger.debug(`Issuer ${issuer} has ${authorizationServerType} Server metadata in well-known location`)\n      if (!authMetadata.authorization_endpoint) {\n        console.warn(\n          `Issuer ${issuer} of type ${authorizationServerType} has no authorization_endpoint! Will use ${authorization_endpoint}. This only works for pre-authorized flows`,\n        )\n      } else if (authorization_endpoint && authMetadata.authorization_endpoint !== authorization_endpoint) {\n        throw Error(\n          `Credential issuer has a different authorization_endpoint (${authorization_endpoint}) from the Authorization Server (${authMetadata.authorization_endpoint})`,\n        )\n      }\n      authorization_endpoint = authMetadata.authorization_endpoint\n      if (authorization_challenge_endpoint && authMetadata.authorization_challenge_endpoint !== authorization_challenge_endpoint) {\n        throw Error(\n          `Credential issuer has a different authorization_challenge_endpoint (${authorization_challenge_endpoint}) from the Authorization Server (${authMetadata.authorization_challenge_endpoint})`,\n        )\n      }\n      authorization_challenge_endpoint = authMetadata.authorization_challenge_endpoint\n      if (!authMetadata.token_endpoint) {\n        throw Error(`Authorization Server ${authorization_servers} did not provide a token_endpoint`)\n      } else if (token_endpoint && authMetadata.token_endpoint !== token_endpoint) {\n        throw Error(\n          `Credential issuer has a different token_endpoint (${token_endpoint}) from the Authorization Server (${authMetadata.token_endpoint})`,\n        )\n      }\n      token_endpoint = authMetadata.token_endpoint\n      if (authMetadata.credential_endpoint) {\n        if (credential_endpoint && authMetadata.credential_endpoint !== credential_endpoint) {\n          logger.debug(\n            `Credential issuer has a different credential_endpoint (${credential_endpoint}) from the Authorization Server (${authMetadata.credential_endpoint}). Will use the issuer value`,\n          )\n        } else {\n          credential_endpoint = authMetadata.credential_endpoint\n        }\n      }\n      if (authMetadata.deferred_credential_endpoint) {\n        if (deferred_credential_endpoint && authMetadata.deferred_credential_endpoint !== deferred_credential_endpoint) {\n          logger.debug(\n            `Credential issuer has a different deferred_credential_endpoint (${deferred_credential_endpoint}) from the Authorization Server (${authMetadata.deferred_credential_endpoint}). Will use the issuer value`,\n          )\n        } else {\n          deferred_credential_endpoint = authMetadata.deferred_credential_endpoint\n        }\n      }\n    }\n\n    if (!authorization_endpoint) {\n      logger.debug(`Issuer ${issuer} does not expose authorization_endpoint, so only pre-auth will be supported`)\n    }\n    if (!token_endpoint) {\n      logger.debug(`Issuer ${issuer} does not have a token_endpoint listed in well-known locations!`)\n      if (opts?.errorOnNotFound) {\n        throw Error(`Could not deduce the token_endpoint for ${issuer}`)\n      } else {\n        token_endpoint = `${issuer}${issuer.endsWith('/') ? 'token' : '/token'}`\n      }\n    }\n    if (!credential_endpoint) {\n      logger.debug(`Issuer ${issuer} does not have a credential_endpoint listed in well-known locations!`)\n      if (opts?.errorOnNotFound) {\n        throw Error(`Could not deduce the credential endpoint for ${issuer}`)\n      } else {\n        credential_endpoint = `${issuer}${issuer.endsWith('/') ? 'credential' : '/credential'}`\n      }\n    }\n\n    if (!credentialIssuerMetadata && authMetadata) {\n      // Apparently everything worked out and the issuer is exposing everything in oAuth2/OIDC well-knowns. Spec is vague about this situation, but we can support it\n      credentialIssuerMetadata = authorization_server\n        ? (authMetadata as CredentialIssuerMetadataV1_0_11)\n        : (authMetadata as CredentialIssuerMetadataV1_0_13)\n    }\n    logger.debug(`Issuer ${issuer} token endpoint ${token_endpoint}, credential endpoint ${credential_endpoint}`)\n\n    return {\n      issuer,\n      token_endpoint,\n      credential_endpoint,\n      deferred_credential_endpoint,\n      ...(authorization_server ? { authorization_server } : { authorization_servers: authorization_servers }),\n      authorization_endpoint,\n      authorization_challenge_endpoint,\n      authorizationServerType,\n      credentialIssuerMetadata: authorization_server\n        ? (credentialIssuerMetadata as IssuerMetadataV1_0_08 & Partial<AuthorizationServerMetadata>)\n        : (credentialIssuerMetadata as CredentialIssuerMetadataV1_0_13),\n      authorizationServerMetadata: authMetadata,\n    } as EndpointMetadataResultV1_0_13 | EndpointMetadataResultV1_0_11\n  }\n\n  /**\n   * Retrieve only the OID4VCI metadata for the issuer. So no OIDC/OAuth2 metadata\n   *\n   * @param issuerHost The issuer hostname\n   * @param opts\n   */\n  public static async retrieveOpenID4VCIServerMetadata(\n    issuerHost: string,\n    opts?: {\n      errorOnNotFound?: boolean\n    },\n  ): Promise<\n    | OpenIDResponse<\n        CredentialIssuerMetadataV1_0_11 | CredentialIssuerMetadataV1_0_13 | (IssuerMetadataV1_0_08 & Partial<AuthorizationServerMetadata>)\n      >\n    | undefined\n  > {\n    return retrieveWellknown(issuerHost, WellKnownEndpoints.OPENID4VCI_ISSUER, {\n      errorOnNotFound: opts?.errorOnNotFound === undefined ? true : opts.errorOnNotFound,\n    })\n  }\n}\n","import {\n  AuthorizationServerMetadata,\n  AuthorizationServerType,\n  CredentialIssuerMetadataV1_0_11,\n  CredentialOfferPayload,\n  CredentialOfferRequestWithBaseUrl,\n  EndpointMetadataResultV1_0_11,\n  getIssuerFromCredentialOfferPayload,\n  IssuerMetadataV1_0_08,\n  OpenIDResponse,\n  WellKnownEndpoints,\n} from '@sphereon/oid4vci-common'\nimport { Loggers } from '@sphereon/ssi-types'\n\nimport { retrieveWellknown } from './functions/OpenIDUtils'\n\nconst logger = Loggers.DEFAULT.get('sphereon:oid4vci:metadata')\n\nexport class MetadataClientV1_0_11 {\n  /**\n   * Retrieve metadata using the Initiation obtained from a previous step\n   *\n   * @param credentialOffer\n   */\n  public static async retrieveAllMetadataFromCredentialOffer(\n    credentialOffer: CredentialOfferRequestWithBaseUrl,\n  ): Promise<EndpointMetadataResultV1_0_11> {\n    return MetadataClientV1_0_11.retrieveAllMetadataFromCredentialOfferRequest(credentialOffer.credential_offer)\n  }\n\n  /**\n   * Retrieve the metada using the initiation request obtained from a previous step\n   * @param request\n   */\n  public static async retrieveAllMetadataFromCredentialOfferRequest(request: CredentialOfferPayload): Promise<EndpointMetadataResultV1_0_11> {\n    const issuer = getIssuerFromCredentialOfferPayload(request)\n    if (issuer) {\n      return MetadataClientV1_0_11.retrieveAllMetadata(issuer)\n    }\n    throw new Error(\"can't retrieve metadata from CredentialOfferRequest. No issuer field is present\")\n  }\n\n  /**\n   * Retrieve all metadata from an issuer\n   * @param issuer The issuer URL\n   * @param opts\n   */\n  public static async retrieveAllMetadata(issuer: string, opts?: { errorOnNotFound: boolean }): Promise<EndpointMetadataResultV1_0_11> {\n    let token_endpoint: string | undefined\n    let credential_endpoint: string | undefined\n    let deferred_credential_endpoint: string | undefined\n    let authorization_endpoint: string | undefined\n    let authorization_challenge_endpoint: string | undefined\n    let authorizationServerType: AuthorizationServerType = 'OID4VCI'\n    let authorization_server: string = issuer\n    const oid4vciResponse = await MetadataClientV1_0_11.retrieveOpenID4VCIServerMetadata(issuer, { errorOnNotFound: false }) // We will handle errors later, given we will also try other metadata locations\n    let credentialIssuerMetadata = oid4vciResponse?.successBody\n    if (credentialIssuerMetadata) {\n      logger.debug(`Issuer ${issuer} OID4VCI well-known server metadata\\r\\n${JSON.stringify(credentialIssuerMetadata)}`)\n      credential_endpoint = credentialIssuerMetadata.credential_endpoint\n      deferred_credential_endpoint = credentialIssuerMetadata.deferred_credential_endpoint\n      if (credentialIssuerMetadata.token_endpoint) {\n        token_endpoint = credentialIssuerMetadata.token_endpoint\n      }\n      authorization_challenge_endpoint = credentialIssuerMetadata.authorization_challenge_endpoint\n      if (credentialIssuerMetadata.authorization_server) {\n        authorization_server = credentialIssuerMetadata.authorization_server\n      }\n      if (credentialIssuerMetadata.authorization_endpoint) {\n        authorization_endpoint = credentialIssuerMetadata.authorization_endpoint\n      }\n    }\n    // No specific OID4VCI endpoint. Either can be an OAuth2 AS or an OIDC IDP. Let's start with OIDC first\n    let response: OpenIDResponse<AuthorizationServerMetadata> = await retrieveWellknown(\n      authorization_server,\n      WellKnownEndpoints.OPENID_CONFIGURATION,\n      {\n        errorOnNotFound: false,\n      },\n    )\n    let authMetadata = response.successBody\n    if (authMetadata) {\n      logger.debug(`Issuer ${issuer} has OpenID Connect Server metadata in well-known location`)\n      authorizationServerType = 'OIDC'\n    } else {\n      // Now let's do OAuth2\n      response = await retrieveWellknown(authorization_server, WellKnownEndpoints.OAUTH_AS, { errorOnNotFound: false })\n      authMetadata = response.successBody\n    }\n    if (!authMetadata) {\n      // We will always throw an error, no matter whether the user provided the option not to, because this is bad.\n      if (issuer !== authorization_server) {\n        throw Error(`Issuer ${issuer} provided a separate authorization server ${authorization_server}, but that server did not provide metadata`)\n      }\n    } else {\n      if (!authorizationServerType) {\n        authorizationServerType = 'OAuth 2.0'\n      }\n      logger.debug(`Issuer ${issuer} has ${authorizationServerType} Server metadata in well-known location`)\n      if (!authMetadata.authorization_endpoint) {\n        console.warn(\n          `Issuer ${issuer} of type ${authorizationServerType} has no authorization_endpoint! Will use ${authorization_endpoint}. This only works for pre-authorized flows`,\n        )\n      } else if (authorization_endpoint && authMetadata.authorization_endpoint !== authorization_endpoint) {\n        throw Error(\n          `Credential issuer has a different authorization_endpoint (${authorization_endpoint}) from the Authorization Server (${authMetadata.authorization_endpoint})`,\n        )\n      }\n      authorization_endpoint = authMetadata.authorization_endpoint\n      if (authorization_challenge_endpoint && authMetadata.authorization_challenge_endpoint !== authorization_challenge_endpoint) {\n        throw Error(\n          `Credential issuer has a different authorization_challenge_endpoint (${authorization_challenge_endpoint}) from the Authorization Server (${authMetadata.authorization_challenge_endpoint})`,\n        )\n      }\n      authorization_challenge_endpoint = authMetadata.authorization_challenge_endpoint\n      if (!authMetadata.token_endpoint) {\n        throw Error(`Authorization Server ${authorization_server} did not provide a token_endpoint`)\n      } else if (token_endpoint && authMetadata.token_endpoint !== token_endpoint) {\n        throw Error(\n          `Credential issuer has a different token_endpoint (${token_endpoint}) from the Authorization Server (${authMetadata.token_endpoint})`,\n        )\n      }\n      token_endpoint = authMetadata.token_endpoint\n      if (authMetadata.credential_endpoint) {\n        if (credential_endpoint && authMetadata.credential_endpoint !== credential_endpoint) {\n          logger.debug(\n            `Credential issuer has a different credential_endpoint (${credential_endpoint}) from the Authorization Server (${authMetadata.credential_endpoint}). Will use the issuer value`,\n          )\n        } else {\n          credential_endpoint = authMetadata.credential_endpoint\n        }\n      }\n      if (authMetadata.deferred_credential_endpoint) {\n        if (deferred_credential_endpoint && authMetadata.deferred_credential_endpoint !== deferred_credential_endpoint) {\n          logger.debug(\n            `Credential issuer has a different deferred_credential_endpoint (${deferred_credential_endpoint}) from the Authorization Server (${authMetadata.deferred_credential_endpoint}). Will use the issuer value`,\n          )\n        } else {\n          deferred_credential_endpoint = authMetadata.deferred_credential_endpoint\n        }\n      }\n    }\n\n    if (!authorization_endpoint) {\n      logger.debug(`Issuer ${issuer} does not expose authorization_endpoint, so only pre-auth will be supported`)\n    }\n    if (!token_endpoint) {\n      logger.debug(`Issuer ${issuer} does not have a token_endpoint listed in well-known locations!`)\n      if (opts?.errorOnNotFound) {\n        throw Error(`Could not deduce the token_endpoint for ${issuer}`)\n      } else {\n        token_endpoint = `${issuer}${issuer.endsWith('/') ? 'token' : '/token'}`\n      }\n    }\n    if (!credential_endpoint) {\n      logger.debug(`Issuer ${issuer} does not have a credential_endpoint listed in well-known locations!`)\n      if (opts?.errorOnNotFound) {\n        throw Error(`Could not deduce the credential endpoint for ${issuer}`)\n      } else {\n        credential_endpoint = `${issuer}${issuer.endsWith('/') ? 'credential' : '/credential'}`\n      }\n    }\n\n    if (!credentialIssuerMetadata && authMetadata) {\n      // Apparently everything worked out and the issuer is exposing everything in oAuth2/OIDC well-knowns. Spec is vague about this situation, but we can support it\n      credentialIssuerMetadata = authMetadata as CredentialIssuerMetadataV1_0_11\n    }\n    logger.debug(`Issuer ${issuer} token endpoint ${token_endpoint}, credential endpoint ${credential_endpoint}`)\n    return {\n      issuer,\n      token_endpoint,\n      credential_endpoint,\n      deferred_credential_endpoint,\n      authorization_server,\n      authorization_endpoint,\n      authorization_challenge_endpoint,\n      authorizationServerType,\n      credentialIssuerMetadata: credentialIssuerMetadata as unknown as Partial<AuthorizationServerMetadata> & IssuerMetadataV1_0_08,\n      authorizationServerMetadata: authMetadata,\n    }\n  }\n\n  /**\n   * Retrieve only the OID4VCI metadata for the issuer. So no OIDC/OAuth2 metadata\n   *\n   * @param issuerHost The issuer hostname\n   */\n  public static async retrieveOpenID4VCIServerMetadata(\n    issuerHost: string,\n    opts?: {\n      errorOnNotFound?: boolean\n    },\n  ): Promise<OpenIDResponse<CredentialIssuerMetadataV1_0_11> | undefined> {\n    return retrieveWellknown(issuerHost, WellKnownEndpoints.OPENID4VCI_ISSUER, {\n      errorOnNotFound: opts?.errorOnNotFound === undefined ? true : opts.errorOnNotFound,\n    })\n  }\n}\n","import {\n  AuthorizationDetails,\n  AuthorizationRequestOpts,\n  CodeChallengeMethod,\n  convertJsonToURI,\n  CreateRequestObjectMode,\n  CredentialOfferFormatV1_0_11,\n  CredentialOfferPayloadV1_0_11,\n  CredentialOfferRequestWithBaseUrl,\n  CredentialsSupportedLegacy,\n  EndpointMetadataResultV1_0_11,\n  formPost,\n  JsonURIMode,\n  PARMode,\n  PKCEOpts,\n  PushedAuthorizationResponse,\n  ResponseType,\n} from '@sphereon/oid4vci-common'\nimport { Loggers } from '@sphereon/ssi-types'\n\nimport { createSignedAuthRequestWhenNeeded } from './AuthorizationCodeClient'\n\nconst logger = Loggers.DEFAULT.get('sphereon:oid4vci')\n\nexport const createAuthorizationRequestUrlV1_0_11 = async ({\n  pkce,\n  endpointMetadata,\n  authorizationRequest,\n  credentialOffer,\n  credentialsSupported,\n}: {\n  pkce: PKCEOpts\n  endpointMetadata: EndpointMetadataResultV1_0_11\n  authorizationRequest: AuthorizationRequestOpts\n  credentialOffer?: CredentialOfferRequestWithBaseUrl\n  credentialsSupported?: CredentialsSupportedLegacy[]\n}): Promise<string> => {\n  const { redirectUri, clientId, requestObjectOpts = { requestObjectMode: CreateRequestObjectMode.NONE } } = authorizationRequest\n  let { scope, authorizationDetails } = authorizationRequest\n\n  const parMode = endpointMetadata?.credentialIssuerMetadata?.require_pushed_authorization_requests\n    ? PARMode.REQUIRE\n    : (authorizationRequest.parMode ?? PARMode.AUTO)\n  // Scope and authorization_details can be used in the same authorization request\n  // https://datatracker.ietf.org/doc/html/draft-ietf-oauth-rar-23#name-relationship-to-scope-param\n  if (!scope && !authorizationDetails) {\n    if (!credentialOffer) {\n      throw Error('Please provide a scope or authorization_details if no credential offer is present')\n    }\n    const creds: (CredentialOfferFormatV1_0_11 | string)[] = (credentialOffer.credential_offer as CredentialOfferPayloadV1_0_11).credentials\n\n    // FIXME: complains about VCT for sd-jwt\n    // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n    // @ts-ignore\n    authorizationDetails = creds\n      .flatMap((cred) => (typeof cred === 'string' ? credentialsSupported : (cred as CredentialsSupportedLegacy)))\n      .filter((cred) => !!cred)\n      .map((cred) => {\n        return {\n          ...cred,\n          type: 'openid_credential',\n          locations: [endpointMetadata.issuer],\n\n          // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n          // @ts-ignore\n          format: cred!.format,\n        } satisfies AuthorizationDetails\n      })\n    if (!authorizationDetails || (Array.isArray(authorizationDetails) && authorizationDetails.length === 0)) {\n      throw Error(`Could not create authorization details from credential offer. Please pass in explicit details`)\n    }\n  }\n  if (!endpointMetadata?.authorization_endpoint) {\n    throw Error('Server metadata does not contain authorization endpoint')\n  }\n  const parEndpoint = endpointMetadata.credentialIssuerMetadata?.pushed_authorization_request_endpoint\n\n  // add 'openid' scope if not present\n  if (!scope?.includes('openid')) {\n    scope = ['openid', scope].filter((s) => !!s).join(' ')\n  }\n\n  let queryObj: { [key: string]: string } | PushedAuthorizationResponse = {\n    response_type: ResponseType.AUTH_CODE,\n    ...(!pkce.disabled && {\n      code_challenge_method: pkce.codeChallengeMethod ?? CodeChallengeMethod.S256,\n      code_challenge: pkce.codeChallenge,\n    }),\n    authorization_details: JSON.stringify(handleAuthorizationDetailsV1_0_11(endpointMetadata, authorizationDetails)),\n    ...(redirectUri && { redirect_uri: redirectUri }),\n    ...(clientId && { client_id: clientId }),\n    ...(credentialOffer?.issuerState && { issuer_state: credentialOffer.issuerState }),\n    scope,\n  }\n\n  if (!parEndpoint && parMode === PARMode.REQUIRE) {\n    throw Error(`PAR mode is set to required by Authorization Server does not support PAR!`)\n  } else if (parEndpoint && parMode !== PARMode.NEVER) {\n    logger.debug(`USING PAR with endpoint ${parEndpoint}`)\n    const parResponse = await formPost<PushedAuthorizationResponse>(\n      parEndpoint,\n      convertJsonToURI(queryObj, {\n        mode: JsonURIMode.X_FORM_WWW_URLENCODED,\n        uriTypeProperties: ['client_id', 'request_uri', 'redirect_uri', 'scope', 'authorization_details', 'issuer_state'],\n      }),\n      { contentType: 'application/x-www-form-urlencoded', accept: 'application/json' },\n    )\n    if (parResponse.errorBody || !parResponse.successBody) {\n      console.log(JSON.stringify(parResponse.errorBody))\n      console.log('Falling back to regular request URI, since PAR failed')\n      if (parMode === PARMode.REQUIRE) {\n        throw Error(`PAR error: ${parResponse.origResponse.statusText}`)\n      }\n    } else {\n      logger.debug(`PAR response: ${JSON.stringify(parResponse.successBody, null, 2)}`)\n      queryObj = { request_uri: parResponse.successBody.request_uri }\n    }\n  }\n  await createSignedAuthRequestWhenNeeded(queryObj, { ...requestObjectOpts, aud: endpointMetadata.authorization_server })\n\n  logger.debug(`Object that will become query params: ` + JSON.stringify(queryObj, null, 2))\n  const url = convertJsonToURI(queryObj, {\n    baseUrl: endpointMetadata.authorization_endpoint,\n    uriTypeProperties: ['client_id', 'request_uri', 'redirect_uri', 'scope', 'authorization_details', 'issuer_state'],\n    // arrayTypeProperties: ['authorization_details'],\n    mode: JsonURIMode.X_FORM_WWW_URLENCODED,\n    // We do not add the version here, as this always needs to be form encoded\n  })\n  logger.debug(`Authorization Request URL: ${url}`)\n  return url\n}\n\nconst handleAuthorizationDetailsV1_0_11 = (\n  endpointMetadata: EndpointMetadataResultV1_0_11,\n  authorizationDetails?: AuthorizationDetails | AuthorizationDetails[],\n): AuthorizationDetails | AuthorizationDetails[] | undefined => {\n  if (authorizationDetails) {\n    if (typeof authorizationDetails === 'string') {\n      // backwards compat for older versions of the lib\n      return authorizationDetails\n    }\n    if (Array.isArray(authorizationDetails)) {\n      return authorizationDetails\n        .filter((value) => typeof value !== 'string')\n        .map((value) => handleLocations(endpointMetadata, typeof value === 'string' ? value : { ...value }))\n    } else {\n      return handleLocations(endpointMetadata, { ...authorizationDetails })\n    }\n  }\n  return authorizationDetails\n}\n\nconst handleLocations = (endpointMetadata: EndpointMetadataResultV1_0_11, authorizationDetails: AuthorizationDetails) => {\n  if (typeof authorizationDetails === 'string') {\n    // backwards compat for older versions of the lib\n    return authorizationDetails\n  }\n  if (authorizationDetails && (endpointMetadata.credentialIssuerMetadata?.authorization_server || endpointMetadata.authorization_endpoint)) {\n    if (authorizationDetails.locations) {\n      if (Array.isArray(authorizationDetails.locations)) {\n        authorizationDetails.locations.push(endpointMetadata.issuer)\n      } else {\n        authorizationDetails.locations = [authorizationDetails.locations as string, endpointMetadata.issuer]\n      }\n    } else {\n      authorizationDetails.locations = [endpointMetadata.issuer]\n    }\n  }\n  return authorizationDetails\n}\n","import { createDPoP, CreateDPoPClientOpts, getCreateDPoPOptions } from '@sphereon/oid4vc-common'\nimport {\n  acquireDeferredCredential,\n  CredentialRequestV1_0_13,\n  CredentialRequestWithoutProofV1_0_13,\n  CredentialResponse,\n  DPoPResponseParams,\n  ExperimentalSubjectIssuance,\n  getCredentialRequestForVersion,\n  getUniformFormat,\n  isDeferredCredentialResponse,\n  isValidURL,\n  OID4VCICredentialFormat,\n  OpenId4VCIVersion,\n  OpenIDResponse,\n  post,\n  ProofOfPossession,\n  UniformCredentialRequest,\n  URL_NOT_VALID,\n} from '@sphereon/oid4vci-common'\nimport { CredentialFormat, Loggers } from '@sphereon/ssi-types'\n\nimport { CredentialRequestClientBuilderV1_0_11 } from './CredentialRequestClientBuilderV1_0_11'\nimport { CredentialRequestClientBuilderV1_0_13 } from './CredentialRequestClientBuilderV1_0_13'\nimport { ProofOfPossessionBuilder } from './ProofOfPossessionBuilder'\nimport { shouldRetryResourceRequestWithDPoPNonce } from './functions/dpopUtil'\n\nconst logger = Loggers.DEFAULT.get('sphereon:oid4vci:credential')\n\nexport interface CredentialRequestOpts {\n  deferredCredentialAwait?: boolean\n  deferredCredentialIntervalInMS?: number\n  credentialEndpoint: string\n  notificationEndpoint?: string\n  deferredCredentialEndpoint?: string\n  credentialTypes?: string[]\n  credentialIdentifier?: string\n  format?: CredentialFormat | OID4VCICredentialFormat\n  proof: ProofOfPossession\n  token: string\n  version: OpenId4VCIVersion\n  subjectIssuance?: ExperimentalSubjectIssuance\n  issuerState?: string\n}\n\nexport type CreateCredentialRequestOpts = {\n  credentialIdentifier?: string\n  credentialTypes?: string | string[]\n  context?: string[]\n  format?: CredentialFormat | OID4VCICredentialFormat\n  subjectIssuance?: ExperimentalSubjectIssuance\n  version: OpenId4VCIVersion\n}\n\nexport async function buildProof(\n  proofInput: ProofOfPossessionBuilder | ProofOfPossession,\n  opts: {\n    version: OpenId4VCIVersion\n    cNonce?: string\n  },\n) {\n  if ('proof_type' in proofInput) {\n    if (opts.cNonce) {\n      throw Error(`Cnonce param is only supported when using a Proof of possession builder`)\n    }\n    return await ProofOfPossessionBuilder.fromProof(proofInput as ProofOfPossession, opts.version).build()\n  }\n  if (opts.cNonce) {\n    proofInput.withAccessTokenNonce(opts.cNonce)\n  }\n  return await proofInput.build()\n}\n\nexport class CredentialRequestClient {\n  private readonly _credentialRequestOpts: Partial<CredentialRequestOpts>\n  private _isDeferred = false\n\n  get credentialRequestOpts(): CredentialRequestOpts {\n    return this._credentialRequestOpts as CredentialRequestOpts\n  }\n\n  public isDeferred(): boolean {\n    return this._isDeferred\n  }\n\n  public getCredentialEndpoint(): string {\n    return this.credentialRequestOpts.credentialEndpoint\n  }\n\n  public getDeferredCredentialEndpoint(): string | undefined {\n    return this.credentialRequestOpts.deferredCredentialEndpoint\n  }\n\n  public constructor(builder: CredentialRequestClientBuilderV1_0_13 | CredentialRequestClientBuilderV1_0_11) {\n    this._credentialRequestOpts = { ...builder }\n  }\n\n  /**\n   * Typically you should not use this method, as it omits a proof from the request.\n   * There are certain issuers that in specific circumstances can do without this proof, because they have other means of user binding\n   * like using DPoP together with an authorization code flow. These are however rare, so you should be using the acquireCredentialsUsingProof normally\n   * @param opts\n   */\n  public async acquireCredentialsWithoutProof(opts: {\n    credentialIdentifier?: string\n    credentialTypes?: string | string[]\n    context?: string[]\n    format?: CredentialFormat | OID4VCICredentialFormat\n    subjectIssuance?: ExperimentalSubjectIssuance\n    createDPoPOpts?: CreateDPoPClientOpts\n  }): Promise<OpenIDResponse<CredentialResponse, DPoPResponseParams> & { access_token: string }> {\n    const { credentialIdentifier, credentialTypes, format, context, subjectIssuance } = opts\n\n    const request = await this.createCredentialRequestWithoutProof({\n      credentialTypes,\n      context,\n      format,\n      version: this.version(),\n      credentialIdentifier,\n      subjectIssuance,\n    })\n    return await this.acquireCredentialsUsingRequestWithoutProof(request, opts.createDPoPOpts)\n  }\n\n  public async acquireCredentialsUsingProof(opts: {\n    proofInput: ProofOfPossessionBuilder | ProofOfPossession\n    credentialIdentifier?: string\n    credentialTypes?: string | string[]\n    context?: string[]\n    format?: CredentialFormat | OID4VCICredentialFormat\n    subjectIssuance?: ExperimentalSubjectIssuance\n    createDPoPOpts?: CreateDPoPClientOpts\n  }): Promise<OpenIDResponse<CredentialResponse, DPoPResponseParams> & { access_token: string }> {\n    const { credentialIdentifier, credentialTypes, proofInput, format, context, subjectIssuance } = opts\n\n    const request = await this.createCredentialRequest({\n      proofInput,\n      credentialTypes,\n      context,\n      format,\n      version: this.version(),\n      credentialIdentifier,\n      subjectIssuance,\n    })\n    return await this.acquireCredentialsUsingRequest(request, opts.createDPoPOpts)\n  }\n\n  public async acquireCredentialsUsingRequestWithoutProof(\n    uniformRequest: UniformCredentialRequest,\n    createDPoPOpts?: CreateDPoPClientOpts,\n  ): Promise<OpenIDResponse<CredentialResponse, DPoPResponseParams> & { access_token: string }> {\n    return await this.acquireCredentialsUsingRequestImpl(uniformRequest, createDPoPOpts)\n  }\n\n  public async acquireCredentialsUsingRequest(\n    uniformRequest: UniformCredentialRequest,\n    createDPoPOpts?: CreateDPoPClientOpts,\n  ): Promise<OpenIDResponse<CredentialResponse, DPoPResponseParams> & { access_token: string }> {\n    return await this.acquireCredentialsUsingRequestImpl(uniformRequest, createDPoPOpts)\n  }\n\n  private async acquireCredentialsUsingRequestImpl(\n    uniformRequest: UniformCredentialRequest & { proof?: ProofOfPossession },\n    createDPoPOpts?: CreateDPoPClientOpts,\n  ): Promise<OpenIDResponse<CredentialResponse, DPoPResponseParams> & { access_token: string }> {\n    if (this.version() < OpenId4VCIVersion.VER_1_0_13) {\n      throw new Error('Versions below v1.0.13 (draft 13) are not supported by the V13 credential request client.')\n    }\n    const request: CredentialRequestV1_0_13 = getCredentialRequestForVersion(uniformRequest, this.version()) as CredentialRequestV1_0_13\n    const credentialEndpoint: string = this.credentialRequestOpts.credentialEndpoint\n    if (!isValidURL(credentialEndpoint)) {\n      logger.debug(`Invalid credential endpoint: ${credentialEndpoint}`)\n      throw new Error(URL_NOT_VALID)\n    }\n    logger.debug(`Acquiring credential(s) from: ${credentialEndpoint}`)\n    logger.debug(`request\\n: ${JSON.stringify(request, null, 2)}`)\n    const requestToken: string = this.credentialRequestOpts.token\n\n    let dPoP = createDPoPOpts ? await createDPoP(getCreateDPoPOptions(createDPoPOpts, credentialEndpoint, { accessToken: requestToken })) : undefined\n\n    let response = (await post(credentialEndpoint, JSON.stringify(request), {\n      bearerToken: requestToken,\n      ...(dPoP && { customHeaders: { dpop: dPoP } }),\n    })) as OpenIDResponse<CredentialResponse> & {\n      access_token: string\n    }\n\n    let nextDPoPNonce = createDPoPOpts?.jwtPayloadProps.nonce\n    const retryWithNonce = shouldRetryResourceRequestWithDPoPNonce(response)\n    if (retryWithNonce.ok && createDPoPOpts) {\n      createDPoPOpts.jwtPayloadProps.nonce = retryWithNonce.dpopNonce\n      dPoP = await createDPoP(getCreateDPoPOptions(createDPoPOpts, credentialEndpoint, { accessToken: requestToken }))\n\n      response = (await post(credentialEndpoint, JSON.stringify(request), {\n        bearerToken: requestToken,\n        ...(createDPoPOpts && { customHeaders: { dpop: dPoP } }),\n      })) as OpenIDResponse<CredentialResponse> & {\n        access_token: string\n      }\n\n      const successDPoPNonce = response.origResponse.headers.get('DPoP-Nonce')\n      nextDPoPNonce = successDPoPNonce ?? retryWithNonce.dpopNonce\n    }\n\n    this._isDeferred = isDeferredCredentialResponse(response)\n    if (this.isDeferred() && this.credentialRequestOpts.deferredCredentialAwait && response.successBody) {\n      response = await this.acquireDeferredCredential(response.successBody, { bearerToken: this.credentialRequestOpts.token })\n    }\n    response.access_token = requestToken\n\n    if ((uniformRequest.credential_subject_issuance && response.successBody) || response.successBody?.credential_subject_issuance) {\n      if (JSON.stringify(uniformRequest.credential_subject_issuance) !== JSON.stringify(response.successBody?.credential_subject_issuance)) {\n        throw Error('Subject signing was requested, but issuer did not provide the options in its response')\n      }\n    }\n    logger.debug(`Credential endpoint ${credentialEndpoint} response:\\r\\n${JSON.stringify(response, null, 2)}`)\n\n    return {\n      ...response,\n      ...(nextDPoPNonce && { params: { dpop: { dpopNonce: nextDPoPNonce } } }),\n    }\n  }\n\n  public async acquireDeferredCredential(\n    response: Pick<CredentialResponse, 'transaction_id' | 'acceptance_token' | 'c_nonce'>,\n    opts?: {\n      bearerToken?: string\n    },\n  ): Promise<OpenIDResponse<CredentialResponse> & { access_token: string }> {\n    const transactionId = response.transaction_id\n    const bearerToken = response.acceptance_token ?? opts?.bearerToken\n    const deferredCredentialEndpoint = this.getDeferredCredentialEndpoint()\n    if (!deferredCredentialEndpoint) {\n      throw Error(`No deferred credential endpoint supplied.`)\n    } else if (!bearerToken) {\n      throw Error(`No bearer token present and refresh for defered endpoint not supported yet`)\n      // todo updated bearer token with new c_nonce\n    }\n    return await acquireDeferredCredential({\n      bearerToken,\n      transactionId,\n      deferredCredentialEndpoint,\n      deferredCredentialAwait: this.credentialRequestOpts.deferredCredentialAwait,\n      deferredCredentialIntervalInMS: this.credentialRequestOpts.deferredCredentialIntervalInMS,\n    })\n  }\n\n  public async createCredentialRequestWithoutProof(opts: CreateCredentialRequestOpts): Promise<CredentialRequestWithoutProofV1_0_13> {\n    return await this.createCredentialRequestImpl(opts)\n  }\n\n  public async createCredentialRequest(\n    opts: CreateCredentialRequestOpts & {\n      proofInput: ProofOfPossessionBuilder | ProofOfPossession\n    },\n  ): Promise<CredentialRequestV1_0_13> {\n    return await this.createCredentialRequestImpl(opts)\n  }\n\n  private async createCredentialRequestImpl(\n    opts: CreateCredentialRequestOpts & {\n      proofInput?: ProofOfPossessionBuilder | ProofOfPossession\n    },\n  ): Promise<CredentialRequestV1_0_13> {\n    const { proofInput, credentialIdentifier: credential_identifier } = opts\n    let proof: ProofOfPossession | undefined = undefined\n    if (proofInput) {\n      proof = await buildProof(proofInput, opts)\n    }\n    if (credential_identifier) {\n      if (opts.format || opts.credentialTypes || opts.context) {\n        throw Error(`You cannot mix credential_identifier with format, credential types and/or context`)\n      }\n      return {\n        credential_identifier,\n        ...(proof && { proof }),\n      }\n    }\n    const formatSelection = opts.format ?? this.credentialRequestOpts.format\n\n    if (!formatSelection) {\n      throw Error(`Format of credential to be issued is missing`)\n    }\n    const format = getUniformFormat(formatSelection)\n    const typesSelection =\n      opts?.credentialTypes && (typeof opts.credentialTypes === 'string' || opts.credentialTypes.length > 0)\n        ? opts.credentialTypes\n        : this.credentialRequestOpts.credentialTypes\n    if (!typesSelection) {\n      throw Error(`Credential type(s) need to be provided`)\n    }\n    const types = Array.isArray(typesSelection) ? typesSelection : [typesSelection]\n    if (types.length === 0) {\n      throw Error(`Credential type(s) need to be provided`)\n    }\n    const issuer_state = this.credentialRequestOpts.issuerState\n\n    // TODO: we should move format specific logic\n    if (format === 'jwt_vc_json' || format === 'jwt_vc') {\n      return {\n        credential_definition: {\n          type: types,\n        },\n        format,\n        ...(issuer_state && { issuer_state }),\n        ...(proof && { proof }),\n        ...opts.subjectIssuance,\n      }\n    } else if (format === 'jwt_vc_json-ld' || format === 'ldp_vc') {\n      if (this.version() >= OpenId4VCIVersion.VER_1_0_12 && !opts.context) {\n        throw Error('No @context value present, but it is required')\n      }\n\n      return {\n        format,\n        ...(issuer_state && { issuer_state }),\n        ...(proof && { proof }),\n        ...opts.subjectIssuance,\n\n        credential_definition: {\n          type: types,\n          '@context': opts.context as string[],\n        },\n      }\n    } else if (format === 'vc+sd-jwt') {\n      if (types.length > 1) {\n        throw Error(`Only a single credential type is supported for ${format}`)\n      }\n      return {\n        format,\n        ...(issuer_state && { issuer_state }),\n        ...(proof && { proof }),\n        vct: types[0],\n        ...opts.subjectIssuance,\n      }\n    } else if (format === 'mso_mdoc') {\n      if (types.length > 1) {\n        throw Error(`Only a single credential type is supported for ${format}`)\n      }\n      return {\n        format,\n        ...(issuer_state && { issuer_state }),\n        ...(proof && { proof }),\n        doctype: types[0],\n        ...opts.subjectIssuance,\n      }\n    }\n\n    throw new Error(`Unsupported credential format: ${format}`)\n  }\n\n  private version(): OpenId4VCIVersion {\n    return this.credentialRequestOpts?.version ?? OpenId4VCIVersion.VER_1_0_13\n  }\n}\n","import {\n  convertJsonToURI,\n  convertURIToJsonObject,\n  CredentialOffer,\n  CredentialOfferPayload,\n  CredentialOfferPayloadV1_0_09,\n  CredentialOfferRequestWithBaseUrl,\n  CredentialOfferV1_0_11,\n  CredentialOfferV1_0_13,\n  determineSpecVersionFromURI,\n  OpenId4VCIVersion,\n  PRE_AUTH_GRANT_LITERAL,\n  toUniformCredentialOfferRequest,\n} from '@sphereon/oid4vci-common'\n\nimport { constructBaseResponse, handleCredentialOfferUri } from './functions'\nimport { LOG } from './types'\n\nexport class CredentialOfferClient {\n  public static async fromURI(uri: string, opts?: { resolve?: boolean }): Promise<CredentialOfferRequestWithBaseUrl> {\n    LOG.debug(`Credential Offer URI: ${uri}`)\n    if (!uri.includes('?') || !uri.includes('://')) {\n      LOG.debug(`Invalid Credential Offer URI: ${uri}`)\n      throw Error(`Invalid Credential Offer Request`)\n    }\n    const scheme = uri.split('://')[0]\n    const baseUrl = uri.split('?')[0]\n    const version = determineSpecVersionFromURI(uri)\n    LOG.log(`Offer URL determined to be of version ${version}`)\n    let credentialOffer: CredentialOffer\n    let credentialOfferPayload: CredentialOfferPayload\n    // credential offer was introduced in draft 9 and credential_offer_uri in draft 11\n    if (version < OpenId4VCIVersion.VER_1_0_11) {\n      credentialOfferPayload = convertURIToJsonObject(uri, {\n        arrayTypeProperties: ['credential_type'],\n        requiredProperties: uri.includes('credential_offer=') ? ['credential_offer'] : ['issuer', 'credential_type'],\n      }) as CredentialOfferPayloadV1_0_09\n      credentialOffer = {\n        credential_offer: credentialOfferPayload,\n      }\n    } else {\n      if (uri.includes('credential_offer_uri')) {\n        credentialOffer = (await handleCredentialOfferUri(uri)) as CredentialOfferV1_0_11 | CredentialOfferV1_0_13\n      } else {\n        credentialOffer = convertURIToJsonObject(uri, {\n          // It must have the '=' sign after credential_offer otherwise the uri will get split at openid_credential_offer\n          arrayTypeProperties: uri.includes('credential_offer_uri=') ? ['credential_offer_uri='] : ['credential_offer='],\n          requiredProperties: uri.includes('credential_offer_uri=') ? ['credential_offer_uri='] : ['credential_offer='],\n        }) as CredentialOfferV1_0_11 | CredentialOfferV1_0_13\n      }\n      if (credentialOffer?.credential_offer_uri === undefined && !credentialOffer?.credential_offer) {\n        throw Error('Either a credential_offer or credential_offer_uri should be present in ' + uri) // cannot be reached since convertURIToJsonObject will check the params\n      }\n    }\n\n    const request = await toUniformCredentialOfferRequest(credentialOffer, {\n      ...opts,\n      version,\n    })\n\n    return {\n      ...constructBaseResponse(request, scheme, baseUrl),\n      userPinRequired:\n        request.credential_offer?.grants?.[PRE_AUTH_GRANT_LITERAL]?.user_pin_required ??\n        !!request.credential_offer?.grants?.[PRE_AUTH_GRANT_LITERAL]?.tx_code ??\n        false,\n    }\n  }\n\n  public static toURI(\n    requestWithBaseUrl: CredentialOfferRequestWithBaseUrl,\n    opts?: {\n      version?: OpenId4VCIVersion\n    },\n  ): string {\n    LOG.debug(`Credential Offer Request with base URL: ${JSON.stringify(requestWithBaseUrl)}`)\n    const version = opts?.version ?? requestWithBaseUrl.version\n    let baseUrl = requestWithBaseUrl.baseUrl.includes(requestWithBaseUrl.scheme)\n      ? requestWithBaseUrl.baseUrl\n      : `${requestWithBaseUrl.scheme.replace('://', '')}://${requestWithBaseUrl.baseUrl}`\n    let param: string | undefined\n\n    const isUri = requestWithBaseUrl.credential_offer_uri !== undefined\n\n    if (version.valueOf() >= OpenId4VCIVersion.VER_1_0_11.valueOf()) {\n      // v11 changed from encoding every param to a encoded json object with a credential_offer param key\n      if (!baseUrl.includes('?')) {\n        param = isUri ? 'credential_offer_uri' : 'credential_offer'\n      } else {\n        const split = baseUrl.split('?')\n        if (split.length > 1 && split[1] !== '') {\n          if (baseUrl.endsWith('&')) {\n            param = isUri ? 'credential_offer_uri' : 'credential_offer'\n          } else if (!baseUrl.endsWith('=')) {\n            baseUrl += `&`\n            param = isUri ? 'credential_offer_uri' : 'credential_offer'\n          }\n        }\n      }\n    }\n    return convertJsonToURI(requestWithBaseUrl.credential_offer_uri ?? requestWithBaseUrl.original_credential_offer, {\n      baseUrl,\n      arrayTypeProperties: isUri ? [] : ['credential_type'],\n      uriTypeProperties: isUri\n        ? ['credential_offer_uri']\n        : version >= OpenId4VCIVersion.VER_1_0_13\n          ? ['credential_issuer', 'credential_type']\n          : ['issuer', 'credential_type'],\n      param,\n      version,\n    })\n  }\n}\n","import {\n  convertJsonToURI,\n  convertURIToJsonObject,\n  CredentialOffer,\n  CredentialOfferPayload,\n  CredentialOfferPayloadV1_0_09,\n  CredentialOfferRequestWithBaseUrl,\n  CredentialOfferRequestWithBaseUrlV1_0_11,\n  CredentialOfferV1_0_11,\n  determineSpecVersionFromURI,\n  getClientIdFromCredentialOfferPayload,\n  OpenId4VCIVersion,\n  PRE_AUTH_CODE_LITERAL,\n  PRE_AUTH_GRANT_LITERAL,\n  toUniformCredentialOfferRequest,\n} from '@sphereon/oid4vci-common'\nimport { Loggers } from '@sphereon/ssi-types'\n\nconst logger = Loggers.DEFAULT.get('sphereon:oid4vci:offer')\n\nexport class CredentialOfferClientV1_0_11 {\n  public static async fromURI(uri: string, opts?: { resolve?: boolean }): Promise<CredentialOfferRequestWithBaseUrlV1_0_11> {\n    logger.debug(`Credential Offer URI: ${uri}`)\n    if (!uri.includes('?') || !uri.includes('://')) {\n      logger.debug(`Invalid Credential Offer URI: ${uri}`)\n      throw Error(`Invalid Credential Offer Request`)\n    }\n    const scheme = uri.split('://')[0]\n    const baseUrl = uri.split('?')[0]\n    const version = determineSpecVersionFromURI(uri)\n    let credentialOffer: CredentialOffer\n    let credentialOfferPayload: CredentialOfferPayload\n    if (version < OpenId4VCIVersion.VER_1_0_11) {\n      credentialOfferPayload = convertURIToJsonObject(uri, {\n        arrayTypeProperties: ['credential_type'],\n        requiredProperties: uri.includes('credential_offer_uri=') ? ['credential_offer_uri='] : ['issuer', 'credential_type='],\n      }) as CredentialOfferPayloadV1_0_09\n      credentialOffer = {\n        credential_offer: credentialOfferPayload,\n      }\n    } else {\n      credentialOffer = convertURIToJsonObject(uri, {\n        arrayTypeProperties: ['credentials'],\n        requiredProperties: uri.includes('credential_offer_uri=') ? ['credential_offer_uri='] : ['credential_offer='],\n      }) as CredentialOfferV1_0_11\n      if (credentialOffer?.credential_offer_uri === undefined && !credentialOffer?.credential_offer) {\n        throw Error('Either a credential_offer or credential_offer_uri should be present in ' + uri) // cannot be reached since convertURIToJsonObject will check the params\n      }\n    }\n\n    const request = await toUniformCredentialOfferRequest(credentialOffer, {\n      ...opts,\n      version,\n    })\n    const clientId = getClientIdFromCredentialOfferPayload(request.credential_offer)\n    const grants = request.credential_offer?.grants\n\n    return {\n      scheme,\n      baseUrl,\n      ...(clientId && { clientId }),\n      ...request,\n      ...(grants?.authorization_code?.issuer_state && { issuerState: grants.authorization_code.issuer_state }),\n      ...(grants?.[PRE_AUTH_GRANT_LITERAL]?.[PRE_AUTH_CODE_LITERAL] && {\n        preAuthorizedCode: grants[PRE_AUTH_GRANT_LITERAL][PRE_AUTH_CODE_LITERAL],\n      }),\n      userPinRequired: !!(request.credential_offer?.grants?.[PRE_AUTH_GRANT_LITERAL]?.user_pin_required ?? false),\n    }\n  }\n\n  public static toURI(\n    requestWithBaseUrl: CredentialOfferRequestWithBaseUrl,\n    opts?: {\n      version?: OpenId4VCIVersion\n    },\n  ): string {\n    logger.debug(`Credential Offer Request with base URL: ${JSON.stringify(requestWithBaseUrl)}`)\n    const version = opts?.version ?? requestWithBaseUrl.version\n    let baseUrl = requestWithBaseUrl.baseUrl.includes(requestWithBaseUrl.scheme)\n      ? requestWithBaseUrl.baseUrl\n      : `${requestWithBaseUrl.scheme.replace('://', '')}://${requestWithBaseUrl.baseUrl}`\n    let param: string | undefined\n\n    const isUri = requestWithBaseUrl.credential_offer_uri !== undefined\n\n    if (version.valueOf() >= OpenId4VCIVersion.VER_1_0_11.valueOf()) {\n      // v11 changed from encoding every param to a encoded json object with a credential_offer param key\n      if (!baseUrl.includes('?')) {\n        param = isUri ? 'credential_offer_uri' : 'credential_offer'\n      } else {\n        const split = baseUrl.split('?')\n        if (split.length > 1 && split[1] !== '') {\n          if (baseUrl.endsWith('&')) {\n            param = isUri ? 'credential_offer_uri' : 'credential_offer'\n          } else if (!baseUrl.endsWith('=')) {\n            baseUrl += `&`\n            param = isUri ? 'credential_offer_uri' : 'credential_offer'\n          }\n        }\n      }\n    }\n    return convertJsonToURI(requestWithBaseUrl.credential_offer_uri ?? requestWithBaseUrl.original_credential_offer, {\n      baseUrl,\n      arrayTypeProperties: isUri ? [] : ['credential_type'],\n      uriTypeProperties: isUri\n        ? ['credential_offer_uri']\n        : version >= OpenId4VCIVersion.VER_1_0_11\n          ? ['credential_issuer', 'credential_type']\n          : ['issuer', 'credential_type'],\n      param,\n      version,\n    })\n  }\n}\n","import {\n  convertJsonToURI,\n  convertURIToJsonObject,\n  CredentialOffer,\n  CredentialOfferRequestWithBaseUrl,\n  CredentialOfferV1_0_13,\n  determineSpecVersionFromURI,\n  OpenId4VCIVersion,\n  PRE_AUTH_GRANT_LITERAL,\n  toUniformCredentialOfferRequest,\n} from '@sphereon/oid4vci-common'\nimport { Loggers } from '@sphereon/ssi-types'\n\nimport { constructBaseResponse, handleCredentialOfferUri } from './functions'\n\nconst logger = Loggers.DEFAULT.get('sphereon:oid4vci:offer')\n\nexport class CredentialOfferClientV1_0_13 {\n  public static async fromURI(uri: string, opts?: { resolve?: boolean }): Promise<CredentialOfferRequestWithBaseUrl> {\n    logger.debug(`Credential Offer URI: ${uri}`)\n    if (!uri.includes('?') || !uri.includes('://')) {\n      logger.debug(`Invalid Credential Offer URI: ${uri}`)\n      throw Error(`Invalid Credential Offer Request`)\n    }\n    const scheme = uri.split('://')[0]\n    const baseUrl = uri.split('?')[0]\n    const version = determineSpecVersionFromURI(uri)\n    let credentialOffer: CredentialOffer\n    if (uri.includes('credential_offer_uri')) {\n      // FIXME deduplicate\n      credentialOffer = (await handleCredentialOfferUri(uri)) as CredentialOfferV1_0_13\n    } else {\n      credentialOffer = convertURIToJsonObject(uri, {\n        // It must have the '=' sign after credential_offer otherwise the uri will get split at openid_credential_offer\n        arrayTypeProperties: uri.includes('credential_offer_uri=')\n          ? ['credential_configuration_ids', 'credential_offer_uri=']\n          : ['credential_configuration_ids', 'credential_offer='],\n        requiredProperties: uri.includes('credential_offer_uri=') ? ['credential_offer_uri='] : ['credential_offer='],\n      }) as CredentialOfferV1_0_13\n    }\n    if (credentialOffer?.credential_offer_uri === undefined && !credentialOffer?.credential_offer) {\n      throw Error('Either a credential_offer or credential_offer_uri should be present in ' + uri) // cannot be reached since convertURIToJsonObject will check the params\n    }\n\n    const request = await toUniformCredentialOfferRequest(credentialOffer, {\n      ...opts,\n      version,\n    })\n\n    return {\n      ...constructBaseResponse(request, scheme, baseUrl),\n      userPinRequired: !!(request.credential_offer?.grants?.[PRE_AUTH_GRANT_LITERAL]?.tx_code ?? false),\n    }\n  }\n\n  public static toURI(\n    requestWithBaseUrl: CredentialOfferRequestWithBaseUrl,\n    opts?: {\n      version?: OpenId4VCIVersion\n    },\n  ): string {\n    logger.debug(`Credential Offer Request with base URL: ${JSON.stringify(requestWithBaseUrl)}`)\n    const version = opts?.version ?? requestWithBaseUrl.version\n    let baseUrl = requestWithBaseUrl.baseUrl.includes(requestWithBaseUrl.scheme)\n      ? requestWithBaseUrl.baseUrl\n      : `${requestWithBaseUrl.scheme.replace('://', '')}://${requestWithBaseUrl.baseUrl}`\n    let param: string | undefined\n\n    const isUri = requestWithBaseUrl.credential_offer_uri !== undefined\n\n    if (version.valueOf() >= OpenId4VCIVersion.VER_1_0_11.valueOf()) {\n      // v11 changed from encoding every param to a encoded json object with a credential_offer param key\n      if (!baseUrl.includes('?')) {\n        param = isUri ? 'credential_offer_uri' : 'credential_offer'\n      } else {\n        const split = baseUrl.split('?')\n        if (split.length > 1 && split[1] !== '') {\n          if (baseUrl.endsWith('&')) {\n            param = isUri ? 'credential_offer_uri' : 'credential_offer'\n          } else if (!baseUrl.endsWith('=')) {\n            baseUrl += `&`\n            param = isUri ? 'credential_offer_uri' : 'credential_offer'\n          }\n        }\n      }\n    }\n    return convertJsonToURI(requestWithBaseUrl.credential_offer_uri ?? requestWithBaseUrl.original_credential_offer, {\n      baseUrl,\n      arrayTypeProperties: isUri ? [] : ['credential_type'],\n      uriTypeProperties: isUri\n        ? ['credential_offer_uri']\n        : version >= OpenId4VCIVersion.VER_1_0_13\n          ? ['credential_issuer', 'credential_type']\n          : ['issuer', 'credential_type'],\n      param,\n      version,\n    })\n  }\n}\n","import { createDPoP, CreateDPoPClientOpts, getCreateDPoPOptions } from '@sphereon/oid4vc-common'\nimport {\n  acquireDeferredCredential,\n  CredentialResponse,\n  DPoPResponseParams,\n  getCredentialRequestForVersion,\n  getUniformFormat,\n  isDeferredCredentialResponse,\n  isValidURL,\n  JsonLdIssuerCredentialDefinition,\n  OID4VCICredentialFormat,\n  OpenId4VCIVersion,\n  OpenIDResponse,\n  post,\n  ProofOfPossession,\n  UniformCredentialRequest,\n  URL_NOT_VALID,\n} from '@sphereon/oid4vci-common'\nimport { CredentialFormat, Loggers } from '@sphereon/ssi-types'\n\nimport { buildProof } from './CredentialRequestClient'\nimport { CredentialRequestClientBuilderV1_0_11 } from './CredentialRequestClientBuilderV1_0_11'\nimport { ProofOfPossessionBuilder } from './ProofOfPossessionBuilder'\nimport { shouldRetryResourceRequestWithDPoPNonce } from './functions/dpopUtil'\n\nconst logger = Loggers.DEFAULT.get('sphereon:oid4vci:credential')\n\nexport interface CredentialRequestOptsV1_0_11 {\n  deferredCredentialAwait?: boolean\n  deferredCredentialIntervalInMS?: number\n  credentialEndpoint: string\n  deferredCredentialEndpoint?: string\n  credentialTypes: string[]\n  format?: CredentialFormat | OID4VCICredentialFormat\n  proof: ProofOfPossession\n  token: string\n  version: OpenId4VCIVersion\n}\n\nexport class CredentialRequestClientV1_0_11 {\n  private readonly _credentialRequestOpts: Partial<CredentialRequestOptsV1_0_11>\n  private _isDeferred = false\n\n  get credentialRequestOpts(): CredentialRequestOptsV1_0_11 {\n    return this._credentialRequestOpts as CredentialRequestOptsV1_0_11\n  }\n\n  public isDeferred(): boolean {\n    return this._isDeferred\n  }\n\n  public getCredentialEndpoint(): string {\n    return this.credentialRequestOpts.credentialEndpoint\n  }\n\n  public getDeferredCredentialEndpoint(): string | undefined {\n    return this.credentialRequestOpts.deferredCredentialEndpoint\n  }\n\n  public constructor(builder: CredentialRequestClientBuilderV1_0_11) {\n    this._credentialRequestOpts = { ...builder }\n  }\n\n  public async acquireCredentialsUsingProof(opts: {\n    proofInput: ProofOfPossessionBuilder | ProofOfPossession\n    credentialTypes?: string | string[]\n    context?: string[]\n    format?: CredentialFormat | OID4VCICredentialFormat\n    createDPoPOpts?: CreateDPoPClientOpts\n  }): Promise<OpenIDResponse<CredentialResponse, DPoPResponseParams> & { access_token: string }> {\n    const { credentialTypes, proofInput, format, context } = opts\n\n    const request = await this.createCredentialRequest({ proofInput, credentialTypes, context, format, version: this.version() })\n    return await this.acquireCredentialsUsingRequest(request, opts.createDPoPOpts)\n  }\n\n  public async acquireCredentialsUsingRequest(\n    uniformRequest: UniformCredentialRequest,\n    createDPoPOpts?: CreateDPoPClientOpts,\n  ): Promise<OpenIDResponse<CredentialResponse, DPoPResponseParams> & { access_token: string }> {\n    const request = getCredentialRequestForVersion(uniformRequest, this.version())\n    const credentialEndpoint: string = this.credentialRequestOpts.credentialEndpoint\n    if (!isValidURL(credentialEndpoint)) {\n      logger.debug(`Invalid credential endpoint: ${credentialEndpoint}`)\n      throw new Error(URL_NOT_VALID)\n    }\n    logger.debug(`Acquiring credential(s) from: ${credentialEndpoint}`)\n    logger.debug(`request\\n: ${JSON.stringify(request, null, 2)}`)\n    const requestToken: string = this.credentialRequestOpts.token\n\n    let dPoP = createDPoPOpts ? await createDPoP(getCreateDPoPOptions(createDPoPOpts, credentialEndpoint, { accessToken: requestToken })) : undefined\n\n    let response = (await post(credentialEndpoint, JSON.stringify(request), {\n      bearerToken: requestToken,\n      customHeaders: { ...(createDPoPOpts && { dpop: dPoP }) },\n    })) as OpenIDResponse<CredentialResponse> & {\n      access_token: string\n    }\n\n    let nextDPoPNonce = createDPoPOpts?.jwtPayloadProps.nonce\n    const retryWithNonce = shouldRetryResourceRequestWithDPoPNonce(response)\n    if (retryWithNonce.ok && createDPoPOpts) {\n      createDPoPOpts.jwtPayloadProps.nonce = retryWithNonce.dpopNonce\n      dPoP = await createDPoP(getCreateDPoPOptions(createDPoPOpts, credentialEndpoint, { accessToken: requestToken }))\n\n      response = (await post(credentialEndpoint, JSON.stringify(request), {\n        bearerToken: requestToken,\n        customHeaders: { ...(createDPoPOpts && { dpop: dPoP }) },\n      })) as OpenIDResponse<CredentialResponse> & {\n        access_token: string\n      }\n\n      const successDPoPNonce = response.origResponse.headers.get('DPoP-Nonce')\n      nextDPoPNonce = successDPoPNonce ?? retryWithNonce.dpopNonce\n    }\n\n    this._isDeferred = isDeferredCredentialResponse(response)\n    if (this.isDeferred() && this.credentialRequestOpts.deferredCredentialAwait && response.successBody) {\n      response = await this.acquireDeferredCredential(response.successBody, { bearerToken: this.credentialRequestOpts.token })\n    }\n    response.access_token = requestToken\n\n    logger.debug(`Credential endpoint ${credentialEndpoint} response:\\r\\n${JSON.stringify(response, null, 2)}`)\n\n    return {\n      ...response,\n      ...(nextDPoPNonce && { params: { dpop: { dpopNonce: nextDPoPNonce } } }),\n    }\n  }\n\n  public async acquireDeferredCredential(\n    response: Pick<CredentialResponse, 'transaction_id' | 'acceptance_token' | 'c_nonce'>,\n    opts?: {\n      bearerToken?: string\n    },\n  ): Promise<OpenIDResponse<CredentialResponse> & { access_token: string }> {\n    const transactionId = response.transaction_id\n    const bearerToken = response.acceptance_token ?? opts?.bearerToken\n    const deferredCredentialEndpoint = this.getDeferredCredentialEndpoint()\n    if (!deferredCredentialEndpoint) {\n      throw Error(`No deferred credential endpoint supplied.`)\n    } else if (!bearerToken) {\n      throw Error(`No bearer token present and refresh for defered endpoint not supported yet`)\n      // todo updated bearer token with new c_nonce\n    }\n    return await acquireDeferredCredential({\n      bearerToken,\n      transactionId,\n      deferredCredentialEndpoint,\n      deferredCredentialAwait: this.credentialRequestOpts.deferredCredentialAwait,\n      deferredCredentialIntervalInMS: this.credentialRequestOpts.deferredCredentialIntervalInMS,\n    })\n  }\n\n  public async createCredentialRequest(opts: {\n    proofInput: ProofOfPossessionBuilder | ProofOfPossession\n    credentialTypes?: string | string[]\n    context?: string[]\n    format?: CredentialFormat | OID4VCICredentialFormat\n    version: OpenId4VCIVersion\n  }): Promise<UniformCredentialRequest> {\n    const { proofInput } = opts\n    const formatSelection = opts.format ?? this.credentialRequestOpts.format\n\n    if (!formatSelection) {\n      throw Error(`Format of credential to be issued is missing`)\n    }\n    const format = getUniformFormat(formatSelection)\n    const typesSelection =\n      opts?.credentialTypes && (typeof opts.credentialTypes === 'string' || opts.credentialTypes.length > 0)\n        ? opts.credentialTypes\n        : this.credentialRequestOpts.credentialTypes\n    const types = Array.isArray(typesSelection) ? typesSelection : [typesSelection]\n    if (types.length === 0) {\n      throw Error(`Credential type(s) need to be provided`)\n    }\n    // FIXME: this is mixing up the type (as id) from v8/v9 and the types (from the vc.type) from v11\n    else if (!this.isV11OrHigher() && types.length !== 1) {\n      throw Error('Only a single credential type is supported for V8/V9')\n    }\n    const proof = await buildProof(proofInput, opts)\n\n    // TODO: we should move format specific logic\n    if (format === 'jwt_vc_json' || format === 'jwt_vc') {\n      return {\n        types,\n        format,\n        proof,\n      }\n    } else if (format === 'jwt_vc_json-ld' || format === 'ldp_vc') {\n      if (this.version() >= OpenId4VCIVersion.VER_1_0_12 && !opts.context) {\n        throw Error('No @context value present, but it is required')\n      }\n\n      return {\n        format,\n        proof,\n\n        // Ignored because v11 does not have the context value, but it is required in v12\n        // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n        // @ts-ignore\n        credential_definition: {\n          types,\n          ...(opts.context && { '@context': opts.context }),\n        } as JsonLdIssuerCredentialDefinition,\n      }\n    } else if (format === 'vc+sd-jwt') {\n      if (types.length > 1) {\n        throw Error(`Only a single credential type is supported for ${format}`)\n      }\n\n      return {\n        format,\n        proof,\n        vct: types[0],\n      }\n    } else if (format === 'mso_mdoc') {\n      if (types.length > 1) {\n        throw Error(`Only a single credential type is supported for ${format}`)\n      }\n\n      return {\n        format,\n        proof,\n        doctype: types[0],\n      }\n    }\n\n    throw new Error(`Unsupported format: ${format}`)\n  }\n\n  private version(): OpenId4VCIVersion {\n    return this.credentialRequestOpts?.version ?? OpenId4VCIVersion.VER_1_0_11\n  }\n\n  private isV11OrHigher(): boolean {\n    return this.version() >= OpenId4VCIVersion.VER_1_0_11\n  }\n}\n","import {\n  AccessTokenResponse,\n  CredentialIssuerMetadata,\n  CredentialIssuerMetadataV1_0_13,\n  CredentialOfferRequestWithBaseUrl,\n  determineSpecVersionFromOffer,\n  EndpointMetadata,\n  ExperimentalSubjectIssuance,\n  OID4VCICredentialFormat,\n  OpenId4VCIVersion,\n  UniformCredentialOfferRequest,\n} from '@sphereon/oid4vci-common'\nimport { CredentialFormat } from '@sphereon/ssi-types'\n\nimport { CredentialOfferClient } from './CredentialOfferClient'\nimport { CredentialRequestClientBuilderV1_0_11 } from './CredentialRequestClientBuilderV1_0_11'\nimport { CredentialRequestClientBuilderV1_0_13 } from './CredentialRequestClientBuilderV1_0_13'\n\ntype CredentialRequestClientBuilderVersionSpecific = CredentialRequestClientBuilderV1_0_11 | CredentialRequestClientBuilderV1_0_13\n\nfunction isV1_0_13(builder: CredentialRequestClientBuilderVersionSpecific): builder is CredentialRequestClientBuilderV1_0_13 {\n  return (builder as CredentialRequestClientBuilderV1_0_13).withCredentialIdentifier !== undefined\n}\n\nexport class CredentialRequestClientBuilder {\n  private _builder: CredentialRequestClientBuilderVersionSpecific\n\n  private constructor(builder: CredentialRequestClientBuilderVersionSpecific) {\n    this._builder = builder\n  }\n\n  public static fromCredentialIssuer({\n    credentialIssuer,\n    metadata,\n    version,\n    credentialIdentifier,\n    credentialTypes,\n  }: {\n    credentialIssuer: string\n    metadata?: EndpointMetadata\n    version?: OpenId4VCIVersion\n    credentialIdentifier?: string\n    credentialTypes?: string | string[]\n  }): CredentialRequestClientBuilder {\n    const specVersion = version ?? OpenId4VCIVersion.VER_1_0_13\n    let builder\n\n    if (specVersion >= OpenId4VCIVersion.VER_1_0_13) {\n      builder = CredentialRequestClientBuilderV1_0_13.fromCredentialIssuer({\n        credentialIssuer,\n        metadata,\n        version,\n        credentialIdentifier,\n        credentialTypes,\n      })\n    } else {\n      if (!credentialTypes || credentialTypes.length === 0) {\n        throw new Error('CredentialTypes must be provided for v1_0_11')\n      }\n      builder = CredentialRequestClientBuilderV1_0_11.fromCredentialIssuer({\n        credentialIssuer,\n        metadata,\n        version,\n        credentialTypes,\n      })\n    }\n\n    return new CredentialRequestClientBuilder(builder)\n  }\n\n  public static async fromURI({ uri, metadata }: { uri: string; metadata?: EndpointMetadata }): Promise<CredentialRequestClientBuilder> {\n    const offer = await CredentialOfferClient.fromURI(uri)\n    return CredentialRequestClientBuilder.fromCredentialOfferRequest({\n      request: offer,\n      ...offer,\n      metadata,\n      version: offer.version,\n    })\n  }\n\n  public static fromCredentialOfferRequest(opts: {\n    request: UniformCredentialOfferRequest\n    scheme?: string\n    baseUrl?: string\n    version?: OpenId4VCIVersion\n    metadata?: EndpointMetadata\n  }): CredentialRequestClientBuilder {\n    const { request } = opts\n    const version = opts.version ?? request.version ?? determineSpecVersionFromOffer(request.original_credential_offer)\n    let builder\n\n    if (version < OpenId4VCIVersion.VER_1_0_13) {\n      builder = CredentialRequestClientBuilderV1_0_11.fromCredentialOfferRequest(opts)\n    } else {\n      builder = CredentialRequestClientBuilderV1_0_13.fromCredentialOfferRequest(opts)\n    }\n\n    return new CredentialRequestClientBuilder(builder)\n  }\n\n  public static fromCredentialOffer({\n    credentialOffer,\n    metadata,\n  }: {\n    credentialOffer: CredentialOfferRequestWithBaseUrl\n    metadata?: EndpointMetadata\n  }): CredentialRequestClientBuilder {\n    const version = determineSpecVersionFromOffer(credentialOffer.credential_offer)\n    let builder\n\n    if (version < OpenId4VCIVersion.VER_1_0_13) {\n      builder = CredentialRequestClientBuilderV1_0_11.fromCredentialOffer({\n        credentialOffer,\n        metadata,\n      })\n    } else {\n      builder = CredentialRequestClientBuilderV1_0_13.fromCredentialOffer({\n        credentialOffer,\n        metadata,\n      })\n    }\n\n    return new CredentialRequestClientBuilder(builder)\n  }\n\n  public getVersion(): OpenId4VCIVersion | undefined {\n    return this._builder.version\n  }\n\n  public withCredentialEndpointFromMetadata(metadata: CredentialIssuerMetadata | CredentialIssuerMetadataV1_0_13): this {\n    if (isV1_0_13(this._builder)) {\n      this._builder.withCredentialEndpointFromMetadata(metadata as CredentialIssuerMetadataV1_0_13)\n    } else {\n      this._builder.withCredentialEndpointFromMetadata(metadata as CredentialIssuerMetadata)\n    }\n    return this\n  }\n\n  public withCredentialEndpoint(credentialEndpoint: string): this {\n    this._builder.withCredentialEndpoint(credentialEndpoint)\n    return this\n  }\n\n  public withDeferredCredentialEndpointFromMetadata(metadata: CredentialIssuerMetadata | CredentialIssuerMetadataV1_0_13): this {\n    if (isV1_0_13(this._builder)) {\n      this._builder.withDeferredCredentialEndpointFromMetadata(metadata as CredentialIssuerMetadataV1_0_13)\n    } else {\n      this._builder.withDeferredCredentialEndpointFromMetadata(metadata as CredentialIssuerMetadata)\n    }\n    return this\n  }\n\n  public withDeferredCredentialEndpoint(deferredCredentialEndpoint: string): this {\n    this._builder.withDeferredCredentialEndpoint(deferredCredentialEndpoint)\n    return this\n  }\n\n  public withDeferredCredentialAwait(deferredCredentialAwait: boolean, deferredCredentialIntervalInMS?: number): this {\n    this._builder.withDeferredCredentialAwait(deferredCredentialAwait, deferredCredentialIntervalInMS)\n    return this\n  }\n\n  public withCredentialIdentifier(credentialIdentifier: string): this {\n    if (this._builder.version === undefined || this._builder.version < OpenId4VCIVersion.VER_1_0_13) {\n      throw new Error('Version of spec should be equal or higher than v1_0_13')\n    }\n    ;(this._builder as CredentialRequestClientBuilderV1_0_13).withCredentialIdentifier(credentialIdentifier)\n    return this\n  }\n\n  public withIssuerState(issuerState?: string): this {\n    this._builder.withIssuerState(issuerState)\n    return this\n  }\n  public withCredentialType(credentialTypes: string | string[]): this {\n    this._builder.withCredentialType(credentialTypes)\n    return this\n  }\n\n  public withFormat(format: CredentialFormat | OID4VCICredentialFormat): this {\n    this._builder.withFormat(format)\n    return this\n  }\n\n  public withSubjectIssuance(subjectIssuance: ExperimentalSubjectIssuance): this {\n    this._builder.withSubjectIssuance(subjectIssuance)\n    return this\n  }\n\n  public withToken(accessToken: string): this {\n    this._builder.withToken(accessToken)\n    return this\n  }\n\n  public withTokenFromResponse(response: AccessTokenResponse): this {\n    this._builder.withTokenFromResponse(response)\n    return this\n  }\n\n  public withVersion(version: OpenId4VCIVersion): this {\n    this._builder.withVersion(version)\n    return this\n  }\n\n  public build() {\n    return this._builder.build()\n  }\n}\n","import {\n  AccessTokenResponse,\n  CredentialIssuerMetadata,\n  CredentialOfferPayloadV1_0_08,\n  CredentialOfferPayloadV1_0_11,\n  CredentialOfferRequestWithBaseUrl,\n  determineSpecVersionFromOffer,\n  EndpointMetadata,\n  ExperimentalSubjectIssuance,\n  getIssuerFromCredentialOfferPayload,\n  getTypesFromOfferV1_0_11,\n  OID4VCICredentialFormat,\n  OpenId4VCIVersion,\n  UniformCredentialOfferRequest,\n} from '@sphereon/oid4vci-common'\nimport { CredentialFormat } from '@sphereon/ssi-types'\n\nimport { CredentialOfferClientV1_0_11 } from './CredentialOfferClientV1_0_11'\nimport { CredentialRequestClientV1_0_11 } from './CredentialRequestClientV1_0_11'\n\nexport class CredentialRequestClientBuilderV1_0_11 {\n  credentialEndpoint?: string\n  deferredCredentialEndpoint?: string\n  deferredCredentialAwait = false\n  deferredCredentialIntervalInMS = 5000\n  credentialTypes: string[] = []\n  format?: CredentialFormat | OID4VCICredentialFormat\n  token?: string\n  version?: OpenId4VCIVersion\n  subjectIssuance?: ExperimentalSubjectIssuance\n  issuerState?: string\n\n  public static fromCredentialIssuer({\n    credentialIssuer,\n    metadata,\n    version,\n    credentialTypes,\n  }: {\n    credentialIssuer: string\n    metadata?: EndpointMetadata\n    version?: OpenId4VCIVersion\n    credentialTypes: string | string[]\n  }): CredentialRequestClientBuilderV1_0_11 {\n    const issuer = credentialIssuer\n    const builder = new CredentialRequestClientBuilderV1_0_11()\n    builder.withVersion(version ?? OpenId4VCIVersion.VER_1_0_11)\n    builder.withCredentialEndpoint(metadata?.credential_endpoint ?? (issuer.endsWith('/') ? `${issuer}credential` : `${issuer}/credential`))\n    if (metadata?.deferred_credential_endpoint) {\n      builder.withDeferredCredentialEndpoint(metadata.deferred_credential_endpoint)\n    }\n    builder.withCredentialType(credentialTypes)\n    return builder\n  }\n\n  public static async fromURI({ uri, metadata }: { uri: string; metadata?: EndpointMetadata }): Promise<CredentialRequestClientBuilderV1_0_11> {\n    const offer = await CredentialOfferClientV1_0_11.fromURI(uri)\n    return CredentialRequestClientBuilderV1_0_11.fromCredentialOfferRequest({ request: offer, ...offer, metadata, version: offer.version })\n  }\n\n  public static fromCredentialOfferRequest(opts: {\n    request: UniformCredentialOfferRequest\n    scheme?: string\n    baseUrl?: string\n    version?: OpenId4VCIVersion\n    metadata?: EndpointMetadata\n  }): CredentialRequestClientBuilderV1_0_11 {\n    const { request, metadata } = opts\n    const version = opts.version ?? request.version ?? determineSpecVersionFromOffer(request.original_credential_offer)\n    const builder = new CredentialRequestClientBuilderV1_0_11()\n    const issuer = getIssuerFromCredentialOfferPayload(request.credential_offer) ?? (metadata?.issuer as string)\n    builder.withVersion(version)\n    builder.withCredentialEndpoint(metadata?.credential_endpoint ?? (issuer.endsWith('/') ? `${issuer}credential` : `${issuer}/credential`))\n    if (metadata?.deferred_credential_endpoint) {\n      builder.withDeferredCredentialEndpoint(metadata.deferred_credential_endpoint)\n    }\n\n    if (version <= OpenId4VCIVersion.VER_1_0_08) {\n      //todo: This basically sets all types available during initiation. Probably the user only wants a subset. So do we want to do this?\n      builder.withCredentialType((request.original_credential_offer as CredentialOfferPayloadV1_0_08).credential_type)\n    } else if (version <= OpenId4VCIVersion.VER_1_0_11) {\n      // todo: look whether this is correct\n      builder.withCredentialType(getTypesFromOfferV1_0_11(request.credential_offer as CredentialOfferPayloadV1_0_11))\n    }\n\n    return builder\n  }\n\n  public static fromCredentialOffer({\n    credentialOffer,\n    metadata,\n  }: {\n    credentialOffer: CredentialOfferRequestWithBaseUrl\n    metadata?: EndpointMetadata\n  }): CredentialRequestClientBuilderV1_0_11 {\n    return CredentialRequestClientBuilderV1_0_11.fromCredentialOfferRequest({\n      request: credentialOffer,\n      metadata,\n      version: credentialOffer.version,\n    })\n  }\n\n  public withIssuerState(issuerState?: string): this {\n    this.issuerState = issuerState\n    return this\n  }\n\n  public withCredentialEndpointFromMetadata(metadata: CredentialIssuerMetadata): this {\n    this.credentialEndpoint = metadata.credential_endpoint\n    return this\n  }\n\n  public withCredentialEndpoint(credentialEndpoint: string): this {\n    this.credentialEndpoint = credentialEndpoint\n    return this\n  }\n\n  public withDeferredCredentialEndpointFromMetadata(metadata: CredentialIssuerMetadata): this {\n    this.deferredCredentialEndpoint = metadata.deferred_credential_endpoint\n    return this\n  }\n\n  public withDeferredCredentialEndpoint(deferredCredentialEndpoint: string): this {\n    this.deferredCredentialEndpoint = deferredCredentialEndpoint\n    return this\n  }\n\n  public withDeferredCredentialAwait(deferredCredentialAwait: boolean, deferredCredentialIntervalInMS?: number): this {\n    this.deferredCredentialAwait = deferredCredentialAwait\n    this.deferredCredentialIntervalInMS = deferredCredentialIntervalInMS ?? 5000\n    return this\n  }\n\n  public withCredentialType(credentialTypes: string | string[]): this {\n    this.credentialTypes = Array.isArray(credentialTypes) ? credentialTypes : [credentialTypes]\n    return this\n  }\n\n  public withFormat(format: CredentialFormat | OID4VCICredentialFormat): this {\n    this.format = format\n    return this\n  }\n\n  public withSubjectIssuance(subjectIssuance: ExperimentalSubjectIssuance): this {\n    this.subjectIssuance = subjectIssuance\n    return this\n  }\n\n  public withToken(accessToken: string): this {\n    this.token = accessToken\n    return this\n  }\n\n  public withTokenFromResponse(response: AccessTokenResponse): this {\n    this.token = response.access_token\n    return this\n  }\n\n  public withVersion(version: OpenId4VCIVersion): this {\n    this.version = version\n    return this\n  }\n\n  public build(): CredentialRequestClientV1_0_11 {\n    if (!this.version) {\n      this.withVersion(OpenId4VCIVersion.VER_1_0_11)\n    }\n    return new CredentialRequestClientV1_0_11(this)\n  }\n}\n","import {\n  AccessTokenResponse,\n  CredentialIssuerMetadataV1_0_13,\n  CredentialOfferPayloadV1_0_13,\n  CredentialOfferRequestWithBaseUrl,\n  determineSpecVersionFromOffer,\n  EndpointMetadata,\n  ExperimentalSubjectIssuance,\n  getIssuerFromCredentialOfferPayload,\n  OID4VCICredentialFormat,\n  OpenId4VCIVersion,\n  UniformCredentialOfferRequest,\n} from '@sphereon/oid4vci-common'\nimport { CredentialFormat } from '@sphereon/ssi-types'\n\nimport { CredentialOfferClient } from './CredentialOfferClient'\nimport { CredentialRequestClient } from './CredentialRequestClient'\n\nexport class CredentialRequestClientBuilderV1_0_13 {\n  credentialEndpoint?: string\n  deferredCredentialEndpoint?: string\n  deferredCredentialAwait = false\n  deferredCredentialIntervalInMS = 5000\n  credentialIdentifier?: string\n  credentialTypes?: string[] = []\n  format?: CredentialFormat | OID4VCICredentialFormat\n  token?: string\n  version?: OpenId4VCIVersion\n  subjectIssuance?: ExperimentalSubjectIssuance\n  issuerState?: string\n\n  public static fromCredentialIssuer({\n    credentialIssuer,\n    metadata,\n    version,\n    credentialIdentifier,\n    credentialTypes,\n  }: {\n    credentialIssuer: string\n    metadata?: EndpointMetadata\n    version?: OpenId4VCIVersion\n    credentialIdentifier?: string\n    credentialTypes?: string | string[]\n  }): CredentialRequestClientBuilderV1_0_13 {\n    const issuer = credentialIssuer\n    const builder = new CredentialRequestClientBuilderV1_0_13()\n    builder.withVersion(version ?? OpenId4VCIVersion.VER_1_0_13)\n    builder.withCredentialEndpoint(metadata?.credential_endpoint ?? (issuer.endsWith('/') ? `${issuer}credential` : `${issuer}/credential`))\n    if (metadata?.deferred_credential_endpoint) {\n      builder.withDeferredCredentialEndpoint(metadata.deferred_credential_endpoint)\n    }\n    if (credentialIdentifier) {\n      builder.withCredentialIdentifier(credentialIdentifier)\n    }\n    if (credentialTypes) {\n      builder.withCredentialType(credentialTypes)\n    }\n    return builder\n  }\n\n  public static async fromURI({ uri, metadata }: { uri: string; metadata?: EndpointMetadata }): Promise<CredentialRequestClientBuilderV1_0_13> {\n    const offer = await CredentialOfferClient.fromURI(uri)\n    return CredentialRequestClientBuilderV1_0_13.fromCredentialOfferRequest({ request: offer, ...offer, metadata, version: offer.version })\n  }\n\n  public static fromCredentialOfferRequest(opts: {\n    request: UniformCredentialOfferRequest\n    scheme?: string\n    baseUrl?: string\n    version?: OpenId4VCIVersion\n    metadata?: EndpointMetadata\n  }): CredentialRequestClientBuilderV1_0_13 {\n    const { request, metadata } = opts\n    const version = opts.version ?? request.version ?? determineSpecVersionFromOffer(request.original_credential_offer)\n    if (version < OpenId4VCIVersion.VER_1_0_13) {\n      throw new Error('Versions below v1.0.13 (draft 13) are not supported.')\n    }\n    const builder = new CredentialRequestClientBuilderV1_0_13()\n    const issuer = getIssuerFromCredentialOfferPayload(request.credential_offer) ?? (metadata?.issuer as string)\n    builder.withVersion(version)\n    builder.withCredentialEndpoint(metadata?.credential_endpoint ?? (issuer.endsWith('/') ? `${issuer}credential` : `${issuer}/credential`))\n    if (metadata?.deferred_credential_endpoint) {\n      builder.withDeferredCredentialEndpoint(metadata.deferred_credential_endpoint)\n    }\n    const ids: string[] = (request.credential_offer as CredentialOfferPayloadV1_0_13).credential_configuration_ids\n    // if there's only one in the offer, we pre-select it. if not, you should provide the credentialType\n    if (ids.length && ids.length === 1) {\n      builder.withCredentialIdentifier(ids[0])\n    }\n\n    return builder\n  }\n\n  public static fromCredentialOffer({\n    credentialOffer,\n    metadata,\n  }: {\n    credentialOffer: CredentialOfferRequestWithBaseUrl\n    metadata?: EndpointMetadata\n  }): CredentialRequestClientBuilderV1_0_13 {\n    const builder = CredentialRequestClientBuilderV1_0_13.fromCredentialOfferRequest({\n      request: credentialOffer,\n      metadata,\n      version: credentialOffer.version,\n    })\n\n    return builder\n  }\n\n  public withCredentialEndpointFromMetadata(metadata: CredentialIssuerMetadataV1_0_13): this {\n    this.credentialEndpoint = metadata.credential_endpoint\n    return this\n  }\n\n  public withCredentialEndpoint(credentialEndpoint: string): this {\n    this.credentialEndpoint = credentialEndpoint\n    return this\n  }\n\n  public withIssuerState(issuerState?: string): this {\n    this.issuerState = issuerState\n    return this\n  }\n\n  public withDeferredCredentialEndpointFromMetadata(metadata: CredentialIssuerMetadataV1_0_13): this {\n    this.deferredCredentialEndpoint = metadata.deferred_credential_endpoint\n    return this\n  }\n\n  public withDeferredCredentialEndpoint(deferredCredentialEndpoint: string): this {\n    this.deferredCredentialEndpoint = deferredCredentialEndpoint\n    return this\n  }\n\n  public withDeferredCredentialAwait(deferredCredentialAwait: boolean, deferredCredentialIntervalInMS?: number): this {\n    this.deferredCredentialAwait = deferredCredentialAwait\n    this.deferredCredentialIntervalInMS = deferredCredentialIntervalInMS ?? 5000\n    return this\n  }\n\n  public withCredentialIdentifier(credentialIdentifier: string): this {\n    this.credentialIdentifier = credentialIdentifier\n    return this\n  }\n\n  public withCredentialType(credentialTypes: string | string[]): this {\n    this.credentialTypes = Array.isArray(credentialTypes) ? credentialTypes : [credentialTypes]\n    return this\n  }\n\n  public withFormat(format: CredentialFormat | OID4VCICredentialFormat): this {\n    this.format = format\n    return this\n  }\n\n  public withSubjectIssuance(subjectIssuance: ExperimentalSubjectIssuance): this {\n    this.subjectIssuance = subjectIssuance\n    return this\n  }\n\n  public withToken(accessToken: string): this {\n    this.token = accessToken\n    return this\n  }\n\n  public withTokenFromResponse(response: AccessTokenResponse): this {\n    this.token = response.access_token\n    return this\n  }\n\n  public withVersion(version: OpenId4VCIVersion): this {\n    this.version = version\n    return this\n  }\n\n  public build(): CredentialRequestClient {\n    if (!this.version) {\n      this.withVersion(OpenId4VCIVersion.VER_1_0_11)\n    }\n    return new CredentialRequestClient(this)\n  }\n}\n","import { CreateDPoPClientOpts, JWK } from '@sphereon/oid4vc-common'\nimport {\n  AccessTokenRequestOpts,\n  AccessTokenResponse,\n  Alg,\n  AuthorizationChallengeCodeResponse,\n  AuthorizationChallengeErrorResponse,\n  AuthorizationChallengeRequestOpts,\n  AuthorizationRequestOpts,\n  AuthorizationResponse,\n  AuthorizationServerOpts,\n  AuthzFlowType,\n  CodeChallengeMethod,\n  CredentialConfigurationSupported,\n  CredentialConfigurationSupportedV1_0_13,\n  CredentialOfferPayloadV1_0_08,\n  CredentialOfferPayloadV1_0_11,\n  CredentialOfferRequestWithBaseUrl,\n  CredentialResponse,\n  CredentialsSupportedLegacy,\n  DefaultURISchemes,\n  determineVersionsFromIssuerMetadata,\n  DPoPResponseParams,\n  EndpointMetadataResultV1_0_11,\n  EndpointMetadataResultV1_0_13,\n  ExperimentalSubjectIssuance,\n  getClientIdFromCredentialOfferPayload,\n  getIssuerFromCredentialOfferPayload,\n  getSupportedCredentials,\n  getTypesFromCredentialSupported,\n  getTypesFromObject,\n  KID_JWK_X5C_ERROR,\n  NotificationRequest,\n  NotificationResponseResult,\n  OID4VCICredentialFormat,\n  OpenId4VCIVersion,\n  PKCEOpts,\n  ProofOfPossessionCallbacks,\n  toAuthorizationResponsePayload,\n} from '@sphereon/oid4vci-common'\nimport { CredentialFormat, Loggers } from '@sphereon/ssi-types'\n\nimport { AccessTokenClient } from './AccessTokenClient'\nimport { AccessTokenClientV1_0_11 } from './AccessTokenClientV1_0_11'\nimport { acquireAuthorizationChallengeAuthCode, createAuthorizationRequestUrl } from './AuthorizationCodeClient'\nimport { createAuthorizationRequestUrlV1_0_11 } from './AuthorizationCodeClientV1_0_11'\nimport { CredentialOfferClient } from './CredentialOfferClient'\nimport { CredentialRequestOpts } from './CredentialRequestClient'\nimport { CredentialRequestClientBuilderV1_0_11 } from './CredentialRequestClientBuilderV1_0_11'\nimport { CredentialRequestClientBuilderV1_0_13 } from './CredentialRequestClientBuilderV1_0_13'\nimport { MetadataClient } from './MetadataClient'\nimport { OpenID4VCIClientStateV1_0_11 } from './OpenID4VCIClientV1_0_11'\nimport { OpenID4VCIClientStateV1_0_13 } from './OpenID4VCIClientV1_0_13'\nimport { ProofOfPossessionBuilder } from './ProofOfPossessionBuilder'\nimport { generateMissingPKCEOpts, sendNotification } from './functions'\n\nconst logger = Loggers.DEFAULT.get('sphereon:oid4vci')\n\nexport type OpenID4VCIClientState = OpenID4VCIClientStateV1_0_11 | OpenID4VCIClientStateV1_0_13\n\nexport type EndpointMetadataResult = EndpointMetadataResultV1_0_11 | EndpointMetadataResultV1_0_13\n\nexport class OpenID4VCIClient {\n  private readonly _state: OpenID4VCIClientState\n\n  private constructor({\n    credentialOffer,\n    clientId,\n    kid,\n    alg,\n    credentialIssuer,\n    pkce,\n    authorizationRequest,\n    accessToken,\n    jwk,\n    endpointMetadata,\n    accessTokenResponse,\n    authorizationRequestOpts,\n    authorizationCodeResponse,\n    authorizationURL,\n  }: {\n    credentialOffer?: CredentialOfferRequestWithBaseUrl\n    kid?: string\n    alg?: Alg | string\n    clientId?: string\n    credentialIssuer?: string\n    pkce?: PKCEOpts\n    authorizationRequest?: AuthorizationRequestOpts // Can be provided here, or when manually calling createAuthorizationUrl\n    jwk?: JWK\n    accessToken?: string\n    endpointMetadata?: EndpointMetadataResult\n    accessTokenResponse?: AccessTokenResponse\n    authorizationRequestOpts?: AuthorizationRequestOpts\n    authorizationCodeResponse?: AuthorizationResponse | AuthorizationChallengeCodeResponse\n    authorizationURL?: string\n  }) {\n    const issuer = credentialIssuer ?? (credentialOffer ? getIssuerFromCredentialOfferPayload(credentialOffer.credential_offer) : undefined)\n    if (!issuer) {\n      throw Error('No credential issuer supplied or deduced from offer')\n    }\n    this._state = {\n      credentialOffer,\n      credentialIssuer: issuer,\n      kid,\n      alg,\n      // TODO: We need to refactor this and always explicitly call createAuthorizationRequestUrl, so we can have a credential selection first and use the kid as a default for the client id\n      clientId: clientId ?? (credentialOffer && getClientIdFromCredentialOfferPayload(credentialOffer.credential_offer)) ?? kid?.split('#')[0],\n      pkce: { disabled: false, codeChallengeMethod: CodeChallengeMethod.S256, ...pkce },\n      authorizationRequestOpts,\n      authorizationCodeResponse,\n      accessToken,\n      jwk,\n      endpointMetadata: endpointMetadata?.credentialIssuerMetadata?.authorization_server\n        ? (endpointMetadata as EndpointMetadataResultV1_0_11)\n        : (endpointMetadata as EndpointMetadataResultV1_0_13 | undefined),\n      accessTokenResponse,\n      authorizationURL,\n    } as OpenID4VCIClientState\n    // Running syncAuthorizationRequestOpts later as it is using the state\n    if (!this._state.authorizationRequestOpts) {\n      this._state.authorizationRequestOpts = this.syncAuthorizationRequestOpts(authorizationRequest)\n    }\n    logger.debug(`Authorization req options: ${JSON.stringify(this._state.authorizationRequestOpts, null, 2)}`)\n  }\n\n  public static async fromCredentialIssuer({\n    kid,\n    alg,\n    retrieveServerMetadata,\n    clientId,\n    credentialIssuer,\n    pkce,\n    authorizationRequest,\n    createAuthorizationRequestURL,\n    endpointMetadata,\n  }: {\n    credentialIssuer: string\n    kid?: string\n    alg?: Alg | string\n    retrieveServerMetadata?: boolean\n    clientId?: string\n    createAuthorizationRequestURL?: boolean\n    authorizationRequest?: AuthorizationRequestOpts // Can be provided here, or when manually calling createAuthorizationUrl\n    pkce?: PKCEOpts\n    endpointMetadata?: EndpointMetadataResult\n  }) {\n    const client = new OpenID4VCIClient({\n      kid,\n      alg,\n      clientId: clientId ?? authorizationRequest?.clientId,\n      credentialIssuer,\n      pkce,\n      authorizationRequest,\n      endpointMetadata,\n    })\n    if (retrieveServerMetadata === undefined || retrieveServerMetadata) {\n      await client.retrieveServerMetadata()\n    }\n    if (createAuthorizationRequestURL === undefined || createAuthorizationRequestURL) {\n      await client.createAuthorizationRequestUrl({ authorizationRequest, pkce })\n    }\n    return client\n  }\n\n  public static async fromState({ state }: { state: OpenID4VCIClientState | string }): Promise<OpenID4VCIClient> {\n    const clientState = typeof state === 'string' ? JSON.parse(state) : state\n\n    return new OpenID4VCIClient(clientState)\n  }\n\n  public static async fromURI({\n    uri,\n    kid,\n    alg,\n    retrieveServerMetadata,\n    clientId,\n    pkce,\n    createAuthorizationRequestURL,\n    authorizationRequest,\n    resolveOfferUri,\n    endpointMetadata,\n  }: {\n    uri: string\n    kid?: string\n    alg?: Alg | string\n    retrieveServerMetadata?: boolean\n    createAuthorizationRequestURL?: boolean\n    resolveOfferUri?: boolean\n    pkce?: PKCEOpts\n    clientId?: string\n    authorizationRequest?: AuthorizationRequestOpts // Can be provided here, or when manually calling createAuthorizationUrl\n    endpointMetadata?: EndpointMetadataResult\n  }): Promise<OpenID4VCIClient> {\n    const credentialOfferClient = await CredentialOfferClient.fromURI(uri, { resolve: resolveOfferUri })\n    const client = new OpenID4VCIClient({\n      credentialOffer: credentialOfferClient,\n      kid,\n      alg,\n      clientId: clientId ?? authorizationRequest?.clientId ?? credentialOfferClient.clientId,\n      pkce,\n      authorizationRequest,\n      endpointMetadata,\n    })\n\n    if (retrieveServerMetadata === undefined || retrieveServerMetadata) {\n      await client.retrieveServerMetadata()\n    }\n    if (\n      credentialOfferClient.supportedFlows.includes(AuthzFlowType.AUTHORIZATION_CODE_FLOW) &&\n      (createAuthorizationRequestURL === undefined || createAuthorizationRequestURL)\n    ) {\n      await client.createAuthorizationRequestUrl({ authorizationRequest, pkce })\n      logger.debug(`Authorization Request URL: ${client._state.authorizationURL}`)\n    }\n\n    return client\n  }\n\n  /**\n   * Allows you to create an Authorization Request URL when using an Authorization Code flow. This URL needs to be accessed using the front channel (browser)\n   *\n   * The Identity provider would present a login screen typically; after you authenticated, it would redirect to the provided redirectUri; which can be same device or cross-device\n   * @param opts\n   */\n  public async createAuthorizationRequestUrl(opts?: { authorizationRequest?: AuthorizationRequestOpts; pkce?: PKCEOpts }): Promise<string> {\n    if (!this._state.authorizationURL) {\n      this.calculatePKCEOpts(opts?.pkce)\n      this._state.authorizationRequestOpts = this.syncAuthorizationRequestOpts(opts?.authorizationRequest)\n      if (!this._state.authorizationRequestOpts) {\n        throw Error(`No Authorization Request options present or provided in this call`)\n      }\n\n      // todo: Probably can go with current logic in MetadataClient who will always set the authorization_endpoint when found\n      //  handling this because of the support for v1_0-08\n      if (\n        this._state.endpointMetadata?.credentialIssuerMetadata &&\n        'authorization_endpoint' in this._state.endpointMetadata.credentialIssuerMetadata\n      ) {\n        this._state.endpointMetadata.authorization_endpoint = this._state.endpointMetadata.credentialIssuerMetadata.authorization_endpoint as string\n      }\n      if (this.version() <= OpenId4VCIVersion.VER_1_0_11) {\n        this._state.authorizationURL = await createAuthorizationRequestUrlV1_0_11({\n          pkce: this._state.pkce,\n          endpointMetadata: this.endpointMetadata as EndpointMetadataResultV1_0_11,\n          authorizationRequest: this._state.authorizationRequestOpts,\n          credentialOffer: this.credentialOffer,\n          credentialsSupported: Object.values(this.getCredentialsSupported(true)) as CredentialsSupportedLegacy[],\n        })\n      } else {\n        this._state.authorizationURL = await createAuthorizationRequestUrl({\n          pkce: this._state.pkce,\n          endpointMetadata: this.endpointMetadata as EndpointMetadataResultV1_0_13,\n          authorizationRequest: this._state.authorizationRequestOpts,\n          credentialOffer: this.credentialOffer,\n          credentialConfigurationSupported: this.getCredentialsSupported(false) as Record<string, CredentialConfigurationSupportedV1_0_13>,\n        })\n      }\n    }\n    return this._state.authorizationURL\n  }\n\n  public async retrieveServerMetadata(): Promise<EndpointMetadataResult> {\n    this.assertIssuerData()\n    if (!this._state.endpointMetadata) {\n      if (this.credentialOffer) {\n        this._state.endpointMetadata = await MetadataClient.retrieveAllMetadataFromCredentialOffer(this.credentialOffer)\n      } else if (this._state.credentialIssuer) {\n        this._state.endpointMetadata = await MetadataClient.retrieveAllMetadata(this._state.credentialIssuer)\n      } else {\n        throw Error(`Cannot retrieve issuer metadata without either a credential offer, or issuer value`)\n      }\n    }\n\n    return this.endpointMetadata\n  }\n\n  private calculatePKCEOpts(pkce?: PKCEOpts) {\n    this._state.pkce = generateMissingPKCEOpts({ ...this._state.pkce, ...pkce })\n  }\n\n  public async acquireAuthorizationChallengeCode(opts?: AuthorizationChallengeRequestOpts): Promise<AuthorizationChallengeCodeResponse> {\n    const response = await acquireAuthorizationChallengeAuthCode({\n      metadata: this.endpointMetadata,\n      credentialIssuer: this.getIssuer(),\n      clientId: this._state.clientId ?? this._state.authorizationRequestOpts?.clientId,\n      ...opts,\n    })\n\n    if (response.errorBody) {\n      logger.debug(`Authorization code error:\\r\\n${JSON.stringify(response.errorBody)}`)\n      const error = response.errorBody as AuthorizationChallengeErrorResponse\n      return Promise.reject(error)\n    } else if (!response.successBody) {\n      logger.debug(`Authorization code error. No success body`)\n      return Promise.reject(\n        Error(\n          `Retrieving an authorization code token from ${this._state.endpointMetadata?.authorization_challenge_endpoint} for issuer ${this.getIssuer()} failed as there was no success response body`,\n        ),\n      )\n    }\n\n    return { ...response.successBody }\n  }\n\n  public async acquireAccessToken(\n    opts?: Omit<AccessTokenRequestOpts, 'credentialOffer' | 'credentialIssuer' | 'metadata' | 'additionalParams'> & {\n      clientId?: string\n      authorizationResponse?: string | AuthorizationResponse | AuthorizationChallengeCodeResponse // Pass in an auth response, either as URI/redirect, or object\n      additionalRequestParams?: Record<string, any>\n    },\n  ): Promise<AccessTokenResponse & { params?: DPoPResponseParams }> {\n    const { pin, clientId = this._state.clientId ?? this._state.authorizationRequestOpts?.clientId } = opts ?? {}\n    let { redirectUri } = opts ?? {}\n\n    const code = this.getAuthorizationCode(opts?.authorizationResponse, opts?.code)\n\n    if (opts?.codeVerifier) {\n      this._state.pkce.codeVerifier = opts.codeVerifier\n    }\n    this.assertIssuerData()\n\n    const asOpts: AuthorizationServerOpts = { ...opts?.asOpts }\n    const kid = asOpts.clientOpts?.kid ?? this._state.kid ?? this._state.authorizationRequestOpts?.requestObjectOpts?.kid\n    const clientAssertionType =\n      asOpts.clientOpts?.clientAssertionType ??\n      (kid && clientId && typeof asOpts.clientOpts?.signCallbacks?.signCallback === 'function'\n        ? 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'\n        : undefined)\n    if (this.isEBSI() || (clientId && kid)) {\n      if (!clientId) {\n        throw Error(`Client id expected for EBSI`)\n      }\n      asOpts.clientOpts = {\n        ...asOpts.clientOpts,\n        clientId,\n        ...(kid && { kid }),\n        ...(clientAssertionType && { clientAssertionType }),\n        signCallbacks: asOpts.clientOpts?.signCallbacks ?? this._state.authorizationRequestOpts?.requestObjectOpts?.signCallbacks,\n      }\n    }\n\n    if (clientId) {\n      this._state.clientId = clientId\n      if (!asOpts.clientOpts) {\n        asOpts.clientOpts = { clientId }\n      }\n      asOpts.clientOpts.clientId = clientId\n    }\n    if (!this._state.accessTokenResponse) {\n      const accessTokenClient = this.version() <= OpenId4VCIVersion.VER_1_0_12 ? new AccessTokenClientV1_0_11() : new AccessTokenClient()\n\n      if (redirectUri && redirectUri !== this._state.authorizationRequestOpts?.redirectUri) {\n        console.log(\n          `Redirect URI mismatch between access-token (${redirectUri}) and authorization request (${this._state.authorizationRequestOpts?.redirectUri}). According to the specification that is not allowed.`,\n        )\n      }\n      if (this._state.authorizationRequestOpts?.redirectUri && !redirectUri) {\n        redirectUri = this._state.authorizationRequestOpts.redirectUri\n      }\n\n      const response = await accessTokenClient.acquireAccessToken({\n        credentialOffer: this.credentialOffer,\n        metadata: this.endpointMetadata,\n        credentialIssuer: this.getIssuer(),\n        pin,\n        ...(!this._state.pkce.disabled && { codeVerifier: this._state.pkce.codeVerifier }),\n        code,\n        redirectUri,\n        asOpts,\n        ...(opts?.createDPoPOpts && { createDPoPOpts: opts.createDPoPOpts }),\n        ...(opts?.additionalRequestParams && { additionalParams: opts.additionalRequestParams }),\n      })\n\n      if (response.errorBody) {\n        logger.debug(`Access token error:\\r\\n${JSON.stringify(response.errorBody)}`)\n        throw Error(\n          `Retrieving an access token from ${this._state.endpointMetadata?.token_endpoint} for issuer ${this.getIssuer()} failed with status: ${\n            response.origResponse.status\n          }`,\n        )\n      } else if (!response.successBody) {\n        logger.debug(`Access token error. No success body`)\n        throw Error(\n          `Retrieving an access token from ${\n            this._state.endpointMetadata?.token_endpoint\n          } for issuer ${this.getIssuer()} failed as there was no success response body`,\n        )\n      }\n      this._state.accessTokenResponse = response.successBody\n      this._state.dpopResponseParams = response.params\n      this._state.accessToken = response.successBody.access_token\n    }\n\n    return { ...this.accessTokenResponse, ...(this.dpopResponseParams && { params: this.dpopResponseParams }) }\n  }\n\n  public async acquireCredentials({\n    credentialTypes,\n    context,\n    proofCallbacks,\n    format,\n    kid,\n    jwk,\n    alg,\n    jti,\n    deferredCredentialAwait,\n    deferredCredentialIntervalInMS,\n    createDPoPOpts,\n  }: {\n    credentialTypes: string | string[]\n    context?: string[]\n    proofCallbacks: ProofOfPossessionCallbacks\n    format?: CredentialFormat | OID4VCICredentialFormat\n    kid?: string\n    jwk?: JWK\n    alg?: Alg | string\n    jti?: string\n    deferredCredentialAwait?: boolean\n    deferredCredentialIntervalInMS?: number\n    experimentalHolderIssuanceSupported?: boolean\n    createDPoPOpts?: CreateDPoPClientOpts\n  }): Promise<CredentialResponse & { params?: DPoPResponseParams; access_token: string }> {\n    if ([jwk, kid].filter((v) => v !== undefined).length > 1) {\n      throw new Error(KID_JWK_X5C_ERROR + `. jwk: ${jwk !== undefined}, kid: ${kid !== undefined}`)\n    }\n\n    if (alg) this._state.alg = alg\n    if (jwk) this._state.jwk = jwk\n    if (kid) this._state.kid = kid\n\n    let requestBuilder: CredentialRequestClientBuilderV1_0_13 | CredentialRequestClientBuilderV1_0_11\n    if (this.version() < OpenId4VCIVersion.VER_1_0_13) {\n      requestBuilder = this.credentialOffer\n        ? CredentialRequestClientBuilderV1_0_11.fromCredentialOffer({\n            credentialOffer: this.credentialOffer,\n            metadata: this.endpointMetadata,\n          })\n        : CredentialRequestClientBuilderV1_0_11.fromCredentialIssuer({\n            credentialIssuer: this.getIssuer(),\n            credentialTypes,\n            metadata: this.endpointMetadata,\n            version: this.version(),\n          })\n    } else {\n      requestBuilder = this.credentialOffer\n        ? CredentialRequestClientBuilderV1_0_13.fromCredentialOffer({\n            credentialOffer: this.credentialOffer,\n            metadata: this.endpointMetadata,\n          })\n        : CredentialRequestClientBuilderV1_0_13.fromCredentialIssuer({\n            credentialIssuer: this.getIssuer(),\n            credentialTypes,\n            metadata: this.endpointMetadata,\n            version: this.version(),\n          })\n    }\n    // If we are in an auth code flow, without a c nonce, we return the issuerState back to the issuer in case it is present\n    const issuerState =\n      this.issuerSupportedFlowTypes().includes(AuthzFlowType.AUTHORIZATION_CODE_FLOW) &&\n      this._state.authorizationCodeResponse &&\n      !this.accessTokenResponse?.c_nonce &&\n      this._state.credentialOffer?.issuerState\n        ? this._state.credentialOffer.issuerState\n        : undefined\n    requestBuilder.withIssuerState(issuerState)\n\n    requestBuilder.withTokenFromResponse(this.accessTokenResponse)\n    requestBuilder.withDeferredCredentialAwait(deferredCredentialAwait ?? false, deferredCredentialIntervalInMS)\n    let subjectIssuance: ExperimentalSubjectIssuance | undefined\n    if (this.endpointMetadata?.credentialIssuerMetadata) {\n      const metadata = this.endpointMetadata.credentialIssuerMetadata\n      const types = Array.isArray(credentialTypes) ? credentialTypes : [credentialTypes]\n\n      if (metadata.credentials_supported && Array.isArray(metadata.credentials_supported)) {\n        let typeSupported = false\n\n        metadata.credentials_supported.forEach((supportedCredential) => {\n          const subTypes = getTypesFromCredentialSupported(supportedCredential)\n          if (\n            subTypes.every((t, i) => types[i] === t) ||\n            (types.length === 1 && (types[0] === supportedCredential.id || subTypes.includes(types[0])))\n          ) {\n            typeSupported = true\n            if (supportedCredential.credential_subject_issuance) {\n              subjectIssuance = { credential_subject_issuance: supportedCredential.credential_subject_issuance }\n            }\n          }\n        })\n\n        if (!typeSupported) {\n          console.log(`Not all credential types ${JSON.stringify(credentialTypes)} are present in metadata for ${this.getIssuer()}`)\n          // throw Error(`Not all credential types ${JSON.stringify(credentialTypes)} are supported by issuer ${this.getIssuer()}`);\n        }\n      } else if (metadata.credentials_supported && !Array.isArray(metadata.credentials_supported)) {\n        const credentialsSupported = metadata.credentials_supported\n        if (types.some((type) => !metadata.credentials_supported || !credentialsSupported[type])) {\n          throw Error(`Not all credential types ${JSON.stringify(credentialTypes)} are supported by issuer ${this.getIssuer()}`)\n        }\n      }\n      // todo: Format check? We might end up with some disjoint type / format combinations supported by the server\n    }\n    if (subjectIssuance) {\n      requestBuilder.withSubjectIssuance(subjectIssuance)\n    }\n\n    const credentialRequestClient = requestBuilder.build()\n    const proofBuilder = ProofOfPossessionBuilder.fromAccessTokenResponse({\n      accessTokenResponse: this.accessTokenResponse,\n      callbacks: proofCallbacks,\n      version: this.version(),\n    })\n      .withIssuer(this.getIssuer())\n      .withAlg(this.alg)\n\n    if (this._state.jwk) {\n      proofBuilder.withJWK(this._state.jwk)\n    }\n    if (this._state.kid) {\n      proofBuilder.withKid(this._state.kid)\n    }\n\n    if (this.clientId) {\n      proofBuilder.withClientId(this.clientId)\n    }\n    if (jti) {\n      proofBuilder.withJti(jti)\n    }\n    const response = await credentialRequestClient.acquireCredentialsUsingProof({\n      proofInput: proofBuilder,\n      credentialTypes,\n      context,\n      format,\n      subjectIssuance,\n      createDPoPOpts,\n    })\n    this._state.dpopResponseParams = response.params\n    if (response.errorBody) {\n      logger.debug(`Credential request error:\\r\\n${JSON.stringify(response.errorBody)}`)\n      throw Error(\n        `Retrieving a credential from ${this._state.endpointMetadata?.credential_endpoint} for issuer ${this.getIssuer()} failed with status: ${\n          response.origResponse.status\n        }`,\n      )\n    } else if (!response.successBody) {\n      logger.debug(`Credential request error. No success body`)\n      throw Error(\n        `Retrieving a credential from ${\n          this._state.endpointMetadata?.credential_endpoint\n        } for issuer ${this.getIssuer()} failed as there was no success response body`,\n      )\n    }\n    return { ...response.successBody, ...(this.dpopResponseParams && { params: this.dpopResponseParams }), access_token: response.access_token }\n  }\n\n  public async exportState(): Promise<string> {\n    return JSON.stringify(this._state)\n  }\n\n  getCredentialsSupported(\n    restrictToInitiationTypes?: boolean,\n    format?: (OID4VCICredentialFormat | string) | (OID4VCICredentialFormat | string)[],\n  ): Record<string, CredentialConfigurationSupportedV1_0_13> | Array<CredentialConfigurationSupported> {\n    return getSupportedCredentials({\n      issuerMetadata: this.endpointMetadata.credentialIssuerMetadata,\n      version: this.version(),\n      format: format,\n      types: restrictToInitiationTypes ? this.getCredentialOfferTypes() : undefined,\n    })\n  }\n\n  public async sendNotification(\n    credentialRequestOpts: Partial<CredentialRequestOpts>,\n    request: NotificationRequest,\n    accessToken?: string,\n  ): Promise<NotificationResponseResult> {\n    return sendNotification(credentialRequestOpts, request, accessToken ?? this._state.accessToken ?? this._state.accessTokenResponse?.access_token)\n  }\n\n  getCredentialOfferTypes(): string[][] | undefined {\n    if (!this.credentialOffer) {\n      return []\n    } else if (this.version() < OpenId4VCIVersion.VER_1_0_11) {\n      const orig = this.credentialOffer.original_credential_offer as CredentialOfferPayloadV1_0_08\n      const types: string[] = typeof orig.credential_type === 'string' ? [orig.credential_type] : orig.credential_type\n      const result: string[][] = []\n      result[0] = types\n      return result\n    } else if (this.version() < OpenId4VCIVersion.VER_1_0_13) {\n      return (this.credentialOffer.credential_offer as CredentialOfferPayloadV1_0_11).credentials.map((c) => getTypesFromObject(c) ?? [])\n    }\n    // we don't have this for v13. v13 only has credential_configuration_ids which is not translatable to type\n    return undefined\n  }\n\n  issuerSupportedFlowTypes(): AuthzFlowType[] {\n    return (\n      this.credentialOffer?.supportedFlows ??\n      ((this._state.endpointMetadata?.credentialIssuerMetadata?.authorization_endpoint ?? this._state.endpointMetadata?.authorization_server)\n        ? [AuthzFlowType.AUTHORIZATION_CODE_FLOW]\n        : [])\n    )\n  }\n\n  isFlowTypeSupported(flowType: AuthzFlowType): boolean {\n    return this.issuerSupportedFlowTypes().includes(flowType)\n  }\n\n  get authorizationURL(): string | undefined {\n    return this._state.authorizationURL\n  }\n\n  public hasAuthorizationURL(): boolean {\n    return !!this.authorizationURL\n  }\n\n  get credentialOffer(): CredentialOfferRequestWithBaseUrl | undefined {\n    return this._state.credentialOffer\n  }\n\n  public version(): OpenId4VCIVersion {\n    if (this.credentialOffer?.version && this.credentialOffer.version !== OpenId4VCIVersion.VER_UNKNOWN) {\n      return this.credentialOffer.version\n    }\n    const metadata = this._state.endpointMetadata\n    if (metadata?.credentialIssuerMetadata) {\n      const versions = determineVersionsFromIssuerMetadata(metadata.credentialIssuerMetadata)\n      if (versions.length > 0 && !versions.includes(OpenId4VCIVersion.VER_UNKNOWN)) {\n        return versions[0]\n      }\n    }\n    return OpenId4VCIVersion.VER_1_0_13\n  }\n\n  public get endpointMetadata(): EndpointMetadataResult {\n    this.assertServerMetadata()\n    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n    return this._state.endpointMetadata!\n  }\n\n  get kid(): string {\n    this.assertIssuerData()\n    if (!this._state.kid) {\n      throw new Error('No value for kid is supplied')\n    }\n    return this._state.kid\n  }\n\n  get alg(): string {\n    this.assertIssuerData()\n    if (!this._state.alg) {\n      throw new Error('No value for alg is supplied')\n    }\n    return this._state.alg\n  }\n\n  set clientId(value: string | undefined) {\n    this._state.clientId = value\n  }\n\n  get clientId(): string | undefined {\n    return this._state.clientId\n  }\n\n  public hasAccessTokenResponse(): boolean {\n    return !!this._state.accessTokenResponse\n  }\n\n  get accessTokenResponse(): AccessTokenResponse {\n    this.assertAccessToken()\n    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n    return this._state.accessTokenResponse!\n  }\n\n  get dpopResponseParams(): DPoPResponseParams | undefined {\n    return this._state.dpopResponseParams\n  }\n\n  public getIssuer(): string {\n    this.assertIssuerData()\n    return this._state.credentialIssuer\n  }\n\n  public getAccessTokenEndpoint(): string {\n    this.assertIssuerData()\n    if (this.endpointMetadata) {\n      return this.endpointMetadata.token_endpoint\n    }\n    return this.version() <= OpenId4VCIVersion.VER_1_0_12\n      ? AccessTokenClientV1_0_11.determineTokenURL({ issuerOpts: { issuer: this.getIssuer() } })\n      : AccessTokenClient.determineTokenURL({ issuerOpts: { issuer: this.getIssuer() } })\n  }\n\n  public getCredentialEndpoint(): string {\n    this.assertIssuerData()\n    return this.endpointMetadata ? this.endpointMetadata.credential_endpoint : `${this.getIssuer()}/credential`\n  }\n\n  public getAuthorizationChallengeEndpoint(): string | undefined {\n    this.assertIssuerData()\n    return this.endpointMetadata?.authorization_challenge_endpoint\n  }\n\n  public hasAuthorizationChallengeEndpoint(): boolean {\n    return !!this.getAuthorizationChallengeEndpoint()\n  }\n\n  public hasDeferredCredentialEndpoint(): boolean {\n    return !!this.getAccessTokenEndpoint()\n  }\n\n  public getDeferredCredentialEndpoint(): string {\n    this.assertIssuerData()\n    return this.endpointMetadata ? this.endpointMetadata.credential_endpoint : `${this.getIssuer()}/credential`\n  }\n\n  /**\n   * Too bad we need a method like this, but EBSI is not exposing metadata\n   */\n  public isEBSI() {\n    if (\n      this.credentialOffer &&\n      (this.credentialOffer?.credential_offer as CredentialOfferPayloadV1_0_11)?.credentials?.find(\n        (cred) =>\n          // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n          // @ts-ignore\n          typeof cred !== 'string' && 'trust_framework' in cred && 'name' in cred.trust_framework && cred.trust_framework.name.includes('ebsi'),\n      )\n    ) {\n      return true\n    }\n    // this.assertIssuerData();\n    return (\n      this.clientId?.includes('ebsi') ||\n      this._state.kid?.includes('did:ebsi:') ||\n      this.getIssuer().includes('ebsi') ||\n      this.endpointMetadata.credentialIssuerMetadata?.authorization_endpoint?.includes('ebsi.eu') ||\n      this.endpointMetadata.credentialIssuerMetadata?.authorization_server?.includes('ebsi.eu')\n    )\n  }\n\n  private assertIssuerData(): void {\n    if (!this._state.credentialIssuer) {\n      throw Error(`No credential issuer value present`)\n    } else if (!this._state.credentialOffer && this._state.endpointMetadata && this.issuerSupportedFlowTypes().length === 0) {\n      throw Error(`No issuance initiation or credential offer present`)\n    }\n  }\n\n  private assertServerMetadata(): void {\n    if (!this._state.endpointMetadata) {\n      throw Error('No server metadata')\n    }\n  }\n\n  private assertAccessToken(): void {\n    if (!this._state.accessTokenResponse) {\n      throw Error(`No access token present`)\n    }\n  }\n\n  private syncAuthorizationRequestOpts(opts?: AuthorizationRequestOpts): AuthorizationRequestOpts {\n    const requestObjectOpts = { ...this._state?.authorizationRequestOpts?.requestObjectOpts, ...opts?.requestObjectOpts }\n    let authorizationRequestOpts = {\n      ...this._state?.authorizationRequestOpts,\n      ...opts,\n      ...(requestObjectOpts && { requestObjectOpts }),\n    } as AuthorizationRequestOpts\n    if (!authorizationRequestOpts) {\n      // We only set a redirectUri if no options are provided.\n      // Note that this only works for mobile apps, that can handle a code query param on the default openid-credential-offer deeplink.\n      // Provide your own options if that is not desired!\n      authorizationRequestOpts = { redirectUri: `${DefaultURISchemes.CREDENTIAL_OFFER}://` }\n    }\n    const clientId = authorizationRequestOpts.clientId ?? this._state.clientId\n    // sync clientId\n    this._state.clientId = clientId\n    authorizationRequestOpts.clientId = clientId\n    return authorizationRequestOpts\n  }\n\n  private getAuthorizationCode = (\n    authorizationResponse?: string | AuthorizationResponse | AuthorizationChallengeCodeResponse,\n    code?: string,\n  ): string | undefined => {\n    if (authorizationResponse) {\n      this._state.authorizationCodeResponse = { ...toAuthorizationResponsePayload(authorizationResponse) }\n    } else if (code) {\n      this._state.authorizationCodeResponse = { code }\n    }\n\n    return (\n      (this._state.authorizationCodeResponse as AuthorizationResponse)?.code ??\n      (this._state.authorizationCodeResponse as AuthorizationChallengeCodeResponse)?.authorization_code\n    )\n  }\n}\n","import { CreateDPoPClientOpts, JWK } from '@sphereon/oid4vc-common'\nimport {\n  AccessTokenRequestOpts,\n  AccessTokenResponse,\n  Alg,\n  AuthorizationChallengeCodeResponse,\n  AuthorizationChallengeErrorResponse,\n  AuthorizationChallengeRequestOpts,\n  AuthorizationRequestOpts,\n  AuthorizationResponse,\n  AuthorizationServerOpts,\n  AuthzFlowType,\n  CodeChallengeMethod,\n  CredentialConfigurationSupportedV1_0_13,\n  CredentialOfferPayloadV1_0_13,\n  CredentialOfferRequestWithBaseUrl,\n  CredentialResponse,\n  DefaultURISchemes,\n  DPoPResponseParams,\n  EndpointMetadataResultV1_0_13,\n  ExperimentalSubjectIssuance,\n  getClientIdFromCredentialOfferPayload,\n  getIssuerFromCredentialOfferPayload,\n  getSupportedCredentials,\n  getTypesFromCredentialSupported,\n  KID_JWK_X5C_ERROR,\n  NotificationRequest,\n  NotificationResponseResult,\n  OID4VCICredentialFormat,\n  OpenId4VCIVersion,\n  PKCEOpts,\n  ProofOfPossessionCallbacks,\n  toAuthorizationResponsePayload,\n} from '@sphereon/oid4vci-common'\nimport { CredentialFormat, Loggers } from '@sphereon/ssi-types'\n\nimport { AccessTokenClient } from './AccessTokenClient'\nimport { acquireAuthorizationChallengeAuthCode, createAuthorizationRequestUrl } from './AuthorizationCodeClient'\nimport { CredentialOfferClient } from './CredentialOfferClient'\nimport { CredentialRequestOpts } from './CredentialRequestClient'\nimport { CredentialRequestClientBuilderV1_0_13 } from './CredentialRequestClientBuilderV1_0_13'\nimport { MetadataClientV1_0_13 } from './MetadataClientV1_0_13'\nimport { ProofOfPossessionBuilder } from './ProofOfPossessionBuilder'\nimport { generateMissingPKCEOpts, sendNotification } from './functions'\n\nconst logger = Loggers.DEFAULT.get('sphereon:oid4vci')\n\nexport interface OpenID4VCIClientStateV1_0_13 {\n  credentialIssuer: string\n  credentialOffer?: CredentialOfferRequestWithBaseUrl\n  clientId?: string\n  kid?: string\n  jwk?: JWK\n  alg?: Alg | string\n  endpointMetadata?: EndpointMetadataResultV1_0_13\n  accessTokenResponse?: AccessTokenResponse\n  dpopResponseParams?: DPoPResponseParams\n  authorizationRequestOpts?: AuthorizationRequestOpts\n  authorizationCodeResponse?: AuthorizationResponse | AuthorizationChallengeCodeResponse\n  pkce: PKCEOpts\n  accessToken?: string\n  authorizationURL?: string\n  sendIssuerStateIfNoNonce?: boolean\n}\n\nexport class OpenID4VCIClientV1_0_13 {\n  private readonly _state: OpenID4VCIClientStateV1_0_13\n\n  private constructor({\n    credentialOffer,\n    clientId,\n    kid,\n    alg,\n    credentialIssuer,\n    pkce,\n    authorizationRequest,\n    accessToken,\n    jwk,\n    endpointMetadata,\n    accessTokenResponse,\n    authorizationRequestOpts,\n    authorizationCodeResponse,\n    authorizationURL,\n  }: {\n    credentialOffer?: CredentialOfferRequestWithBaseUrl\n    kid?: string\n    alg?: Alg | string\n    clientId?: string\n    credentialIssuer?: string\n    pkce?: PKCEOpts\n    authorizationRequest?: AuthorizationRequestOpts // Can be provided here, or when manually calling createAuthorizationUrl\n    jwk?: JWK\n    accessToken?: string\n    endpointMetadata?: EndpointMetadataResultV1_0_13\n    accessTokenResponse?: AccessTokenResponse\n    authorizationRequestOpts?: AuthorizationRequestOpts\n    authorizationCodeResponse?: AuthorizationResponse | AuthorizationChallengeCodeResponse\n    authorizationURL?: string\n  }) {\n    const issuer = credentialIssuer ?? (credentialOffer ? getIssuerFromCredentialOfferPayload(credentialOffer.credential_offer) : undefined)\n    if (!issuer) {\n      throw Error('No credential issuer supplied or deduced from offer')\n    }\n    this._state = {\n      credentialOffer,\n      credentialIssuer: issuer,\n      kid,\n      alg,\n      // TODO: We need to refactor this and always explicitly call createAuthorizationRequestUrl, so we can have a credential selection first and use the kid as a default for the client id\n      clientId: clientId ?? (credentialOffer && getClientIdFromCredentialOfferPayload(credentialOffer.credential_offer)) ?? kid?.split('#')[0],\n      pkce: { disabled: false, codeChallengeMethod: CodeChallengeMethod.S256, ...pkce },\n      authorizationRequestOpts,\n      authorizationCodeResponse,\n      accessToken,\n      jwk,\n      endpointMetadata,\n      accessTokenResponse,\n      authorizationURL,\n    }\n    // Running syncAuthorizationRequestOpts later as it is using the state\n    if (!this._state.authorizationRequestOpts) {\n      this._state.authorizationRequestOpts = this.syncAuthorizationRequestOpts(authorizationRequest)\n    }\n    logger.debug(`Authorization req options: ${JSON.stringify(this._state.authorizationRequestOpts, null, 2)}`)\n  }\n\n  public static async fromCredentialIssuer({\n    kid,\n    alg,\n    retrieveServerMetadata,\n    clientId,\n    credentialIssuer,\n    pkce,\n    authorizationRequest,\n    createAuthorizationRequestURL,\n  }: {\n    credentialIssuer: string\n    kid?: string\n    alg?: Alg | string\n    retrieveServerMetadata?: boolean\n    clientId?: string\n    createAuthorizationRequestURL?: boolean\n    authorizationRequest?: AuthorizationRequestOpts // Can be provided here, or when manually calling createAuthorizationUrl\n    pkce?: PKCEOpts\n  }) {\n    const client = new OpenID4VCIClientV1_0_13({\n      kid,\n      alg,\n      clientId: clientId ?? authorizationRequest?.clientId,\n      credentialIssuer,\n      pkce,\n      authorizationRequest,\n    })\n    if (retrieveServerMetadata === undefined || retrieveServerMetadata) {\n      await client.retrieveServerMetadata()\n    }\n    if (createAuthorizationRequestURL === undefined || createAuthorizationRequestURL) {\n      await client.createAuthorizationRequestUrl({ authorizationRequest, pkce })\n    }\n    return client\n  }\n\n  public static async fromState({ state }: { state: OpenID4VCIClientStateV1_0_13 | string }): Promise<OpenID4VCIClientV1_0_13> {\n    const clientState = typeof state === 'string' ? JSON.parse(state) : state\n\n    return new OpenID4VCIClientV1_0_13(clientState)\n  }\n\n  public static async fromURI({\n    uri,\n    kid,\n    alg,\n    retrieveServerMetadata,\n    clientId,\n    pkce,\n    createAuthorizationRequestURL,\n    authorizationRequest,\n    resolveOfferUri,\n  }: {\n    uri: string\n    kid?: string\n    alg?: Alg | string\n    retrieveServerMetadata?: boolean\n    createAuthorizationRequestURL?: boolean\n    resolveOfferUri?: boolean\n    pkce?: PKCEOpts\n    clientId?: string\n    authorizationRequest?: AuthorizationRequestOpts // Can be provided here, or when manually calling createAuthorizationUrl\n  }): Promise<OpenID4VCIClientV1_0_13> {\n    const credentialOfferClient = await CredentialOfferClient.fromURI(uri, { resolve: resolveOfferUri })\n    const client = new OpenID4VCIClientV1_0_13({\n      credentialOffer: credentialOfferClient,\n      kid,\n      alg,\n      clientId: clientId ?? authorizationRequest?.clientId ?? credentialOfferClient.clientId,\n      pkce,\n      authorizationRequest,\n    })\n\n    if (retrieveServerMetadata === undefined || retrieveServerMetadata) {\n      await client.retrieveServerMetadata()\n    }\n    if (\n      credentialOfferClient.supportedFlows.includes(AuthzFlowType.AUTHORIZATION_CODE_FLOW) &&\n      (createAuthorizationRequestURL === undefined || createAuthorizationRequestURL)\n    ) {\n      await client.createAuthorizationRequestUrl({ authorizationRequest, pkce })\n      logger.debug(`Authorization Request URL: ${client._state.authorizationURL}`)\n    }\n\n    return client\n  }\n\n  /**\n   * Allows you to create an Authorization Request URL when using an Authorization Code flow. This URL needs to be accessed using the front channel (browser)\n   *\n   * The Identity provider would present a login screen typically; after you authenticated, it would redirect to the provided redirectUri; which can be same device or cross-device\n   * @param opts\n   */\n  public async createAuthorizationRequestUrl(opts?: { authorizationRequest?: AuthorizationRequestOpts; pkce?: PKCEOpts }): Promise<string> {\n    if (!this._state.authorizationURL) {\n      this.calculatePKCEOpts(opts?.pkce)\n      this._state.authorizationRequestOpts = this.syncAuthorizationRequestOpts(opts?.authorizationRequest)\n      if (!this._state.authorizationRequestOpts) {\n        throw Error(`No Authorization Request options present or provided in this call`)\n      }\n\n      // todo: Probably can go with current logic in MetadataClientV1_0_13 who will always set the authorization_endpoint when found\n      //  handling this because of the support for v1_0-08\n      if (\n        this._state.endpointMetadata?.credentialIssuerMetadata &&\n        'authorization_endpoint' in this._state.endpointMetadata.credentialIssuerMetadata\n      ) {\n        this._state.endpointMetadata.authorization_endpoint = this._state.endpointMetadata.credentialIssuerMetadata.authorization_endpoint as string\n      }\n      this._state.authorizationURL = await createAuthorizationRequestUrl({\n        pkce: this._state.pkce,\n        endpointMetadata: this.endpointMetadata,\n        authorizationRequest: this._state.authorizationRequestOpts,\n        credentialOffer: this.credentialOffer,\n        credentialConfigurationSupported: this.getCredentialsSupported(),\n        version: this.version(),\n      })\n    }\n    return this._state.authorizationURL\n  }\n\n  public async retrieveServerMetadata(): Promise<EndpointMetadataResultV1_0_13> {\n    this.assertIssuerData()\n    if (!this._state.endpointMetadata) {\n      if (this.credentialOffer) {\n        this._state.endpointMetadata = await MetadataClientV1_0_13.retrieveAllMetadataFromCredentialOffer(this.credentialOffer)\n      } else if (this._state.credentialIssuer) {\n        this._state.endpointMetadata = await MetadataClientV1_0_13.retrieveAllMetadata(this._state.credentialIssuer)\n      } else {\n        throw Error(`Cannot retrieve issuer metadata without either a credential offer, or issuer value`)\n      }\n    }\n\n    return this.endpointMetadata\n  }\n\n  private calculatePKCEOpts(pkce?: PKCEOpts) {\n    this._state.pkce = generateMissingPKCEOpts({ ...this._state.pkce, ...pkce })\n  }\n\n  public async acquireAuthorizationChallengeCode(opts?: AuthorizationChallengeRequestOpts): Promise<AuthorizationChallengeCodeResponse> {\n    const response = await acquireAuthorizationChallengeAuthCode({\n      metadata: this.endpointMetadata,\n      credentialIssuer: this.getIssuer(),\n      clientId: this._state.clientId ?? this._state.authorizationRequestOpts?.clientId,\n      ...opts,\n    })\n\n    if (response.errorBody) {\n      logger.debug(`Authorization code error:\\r\\n${JSON.stringify(response.errorBody)}`)\n      const error = response.errorBody as AuthorizationChallengeErrorResponse\n      return Promise.reject(error)\n    } else if (!response.successBody) {\n      logger.debug(`Authorization code error. No success body`)\n      return Promise.reject(\n        Error(\n          `Retrieving an authorization code token from ${this._state.endpointMetadata?.authorization_challenge_endpoint} for issuer ${this.getIssuer()} failed as there was no success response body`,\n        ),\n      )\n    }\n\n    return { ...response.successBody }\n  }\n\n  public async acquireAccessToken(\n    opts?: Omit<AccessTokenRequestOpts, 'credentialOffer' | 'credentialIssuer' | 'metadata' | 'additionalParams'> & {\n      clientId?: string\n      authorizationResponse?: string | AuthorizationResponse | AuthorizationChallengeCodeResponse // Pass in an auth response, either as URI/redirect, or object\n      additionalRequestParams?: Record<string, any>\n    },\n  ): Promise<AccessTokenResponse & { params?: DPoPResponseParams }> {\n    const { pin, clientId = this._state.clientId ?? this._state.authorizationRequestOpts?.clientId } = opts ?? {}\n    let { redirectUri } = opts ?? {}\n\n    const code = this.getAuthorizationCode(opts?.authorizationResponse, opts?.code)\n\n    if (opts?.codeVerifier) {\n      this._state.pkce.codeVerifier = opts.codeVerifier\n    }\n    this.assertIssuerData()\n    const asOpts: AuthorizationServerOpts = { ...opts?.asOpts }\n    const kid = asOpts.clientOpts?.kid ?? this._state.kid ?? this._state.authorizationRequestOpts?.requestObjectOpts?.kid\n    const clientAssertionType =\n      asOpts.clientOpts?.clientAssertionType ??\n      (kid && clientId && typeof asOpts.clientOpts?.signCallbacks?.signCallback === 'function'\n        ? 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'\n        : undefined)\n    if (this.isEBSI() || (clientId && kid)) {\n      if (!clientId) {\n        throw Error(`Client id expected for EBSI`)\n      }\n      asOpts.clientOpts = {\n        ...asOpts.clientOpts,\n        clientId,\n        ...(kid && { kid }),\n        ...(clientAssertionType && { clientAssertionType }),\n        signCallbacks: asOpts.clientOpts?.signCallbacks ?? this._state.authorizationRequestOpts?.requestObjectOpts?.signCallbacks,\n      }\n    }\n\n    if (clientId) {\n      this._state.clientId = clientId\n      if (!asOpts.clientOpts) {\n        asOpts.clientOpts = { clientId }\n      }\n      asOpts.clientOpts.clientId = clientId\n    }\n    if (!this._state.accessTokenResponse) {\n      const accessTokenClient = new AccessTokenClient()\n\n      if (redirectUri && redirectUri !== this._state.authorizationRequestOpts?.redirectUri) {\n        console.log(\n          `Redirect URI mismatch between access-token (${redirectUri}) and authorization request (${this._state.authorizationRequestOpts?.redirectUri}). According to the specification that is not allowed.`,\n        )\n      }\n      if (this._state.authorizationRequestOpts?.redirectUri && !redirectUri) {\n        redirectUri = this._state.authorizationRequestOpts.redirectUri\n      }\n      const response = await accessTokenClient.acquireAccessToken({\n        credentialOffer: this.credentialOffer,\n        metadata: this.endpointMetadata,\n        credentialIssuer: this.getIssuer(),\n        pin,\n        ...(!this._state.pkce.disabled && { codeVerifier: this._state.pkce.codeVerifier }),\n        code,\n        redirectUri,\n        asOpts,\n        ...(opts?.createDPoPOpts && { createDPoPOpts: opts.createDPoPOpts }),\n        ...(opts?.additionalRequestParams && { additionalParams: opts.additionalRequestParams }),\n      })\n\n      if (response.errorBody) {\n        logger.debug(`Access token error:\\r\\n${JSON.stringify(response.errorBody)}`)\n        throw Error(\n          `Retrieving an access token from ${this._state.endpointMetadata?.token_endpoint} for issuer ${this.getIssuer()} failed with status: ${\n            response.origResponse.status\n          }`,\n        )\n      } else if (!response.successBody) {\n        logger.debug(`Access token error. No success body`)\n        throw Error(\n          `Retrieving an access token from ${\n            this._state.endpointMetadata?.token_endpoint\n          } for issuer ${this.getIssuer()} failed as there was no success response body`,\n        )\n      }\n      this._state.accessTokenResponse = response.successBody\n      this._state.dpopResponseParams = response.params\n      this._state.accessToken = response.successBody.access_token\n    }\n\n    return { ...this.accessTokenResponse, ...(this.dpopResponseParams && { params: this.dpopResponseParams }) }\n  }\n\n  public async acquireCredentialsWithoutProof(args: {\n    credentialIdentifier?: string\n    credentialTypes?: string | string[]\n    context?: string[]\n    format?: CredentialFormat | OID4VCICredentialFormat\n    kid?: string\n    jwk?: JWK\n    alg?: Alg | string\n    jti?: string\n    deferredCredentialAwait?: boolean\n    deferredCredentialIntervalInMS?: number\n    experimentalHolderIssuanceSupported?: boolean\n    createDPoPOpts?: CreateDPoPClientOpts\n  }): Promise<CredentialResponse & { access_token: string }> {\n    return await this.acquireCredentialsImpl(args)\n  }\n  public async acquireCredentials(args: {\n    credentialIdentifier?: string\n    credentialTypes?: string | string[]\n    context?: string[]\n    proofCallbacks: ProofOfPossessionCallbacks\n    format?: CredentialFormat | OID4VCICredentialFormat\n    kid?: string\n    jwk?: JWK\n    alg?: Alg | string\n    jti?: string\n    deferredCredentialAwait?: boolean\n    deferredCredentialIntervalInMS?: number\n    experimentalHolderIssuanceSupported?: boolean\n    createDPoPOpts?: CreateDPoPClientOpts\n  }): Promise<CredentialResponse & { access_token: string }> {\n    return await this.acquireCredentialsImpl(args)\n  }\n\n  private async acquireCredentialsImpl({\n    credentialIdentifier,\n    credentialTypes,\n    context,\n    proofCallbacks,\n    format,\n    kid,\n    jwk,\n    alg,\n    jti,\n    deferredCredentialAwait,\n    deferredCredentialIntervalInMS,\n    createDPoPOpts,\n  }: {\n    credentialIdentifier?: string\n    credentialTypes?: string | string[]\n    context?: string[]\n    proofCallbacks?: ProofOfPossessionCallbacks\n    format?: CredentialFormat | OID4VCICredentialFormat\n    kid?: string\n    jwk?: JWK\n    alg?: Alg | string\n    jti?: string\n    deferredCredentialAwait?: boolean\n    deferredCredentialIntervalInMS?: number\n    experimentalHolderIssuanceSupported?: boolean\n    createDPoPOpts?: CreateDPoPClientOpts\n  }): Promise<CredentialResponse & { access_token: string }> {\n    if ([jwk, kid].filter((v) => v !== undefined).length > 1) {\n      throw new Error(KID_JWK_X5C_ERROR + `. jwk: ${jwk !== undefined}, kid: ${kid !== undefined}`)\n    }\n\n    if (alg) this._state.alg = alg\n    if (jwk) this._state.jwk = jwk\n    if (kid) this._state.kid = kid\n\n    const requestBuilder = this.credentialOffer\n      ? CredentialRequestClientBuilderV1_0_13.fromCredentialOffer({\n          credentialOffer: this.credentialOffer,\n          metadata: this.endpointMetadata,\n        })\n      : CredentialRequestClientBuilderV1_0_13.fromCredentialIssuer({\n          credentialIssuer: this.getIssuer(),\n          credentialIdentifier: credentialIdentifier,\n          metadata: this.endpointMetadata,\n          version: this.version(),\n        })\n    // If we are in an auth code flow, without a c nonce, we return the issuerState back to the issuer in case it is present\n    const issuerState =\n      this.issuerSupportedFlowTypes().includes(AuthzFlowType.AUTHORIZATION_CODE_FLOW) &&\n      this._state.authorizationCodeResponse &&\n      !this.accessTokenResponse?.c_nonce &&\n      this._state.credentialOffer?.issuerState\n        ? this._state.credentialOffer.issuerState\n        : undefined\n    requestBuilder.withIssuerState(issuerState)\n    requestBuilder.withTokenFromResponse(this.accessTokenResponse)\n    requestBuilder.withDeferredCredentialAwait(deferredCredentialAwait ?? false, deferredCredentialIntervalInMS)\n    let subjectIssuance: ExperimentalSubjectIssuance | undefined\n    if (this.endpointMetadata?.credentialIssuerMetadata) {\n      const metadata = this.endpointMetadata.credentialIssuerMetadata\n      const types = credentialTypes ? (Array.isArray(credentialTypes) ? credentialTypes : [credentialTypes]) : undefined\n\n      if (credentialIdentifier) {\n        if (typeof metadata.credential_configurations_supported !== 'object') {\n          throw Error(\n            `Credentials_supported should be an object, current ${typeof metadata.credential_configurations_supported} when credential_identifier is used`,\n          )\n        }\n        const credentialsSupported = metadata.credential_configurations_supported\n        if (!credentialsSupported || !credentialsSupported[credentialIdentifier]) {\n          throw new Error(`Credential type ${credentialIdentifier} is not supported by issuer ${this.getIssuer()}`)\n        }\n      } else if (!types) {\n        throw Error(`If no credential_identifier is used, we expect types`)\n      } else if (metadata.credentials_supported && Array.isArray(metadata.credentials_supported)) {\n        let typeSupported = false\n\n        metadata.credentials_supported.forEach((supportedCredential) => {\n          const subTypes = getTypesFromCredentialSupported(supportedCredential)\n          if (\n            subTypes.every((t, i) => types[i] === t) ||\n            (types.length === 1 && (types[0] === supportedCredential.id || subTypes.includes(types[0])))\n          ) {\n            typeSupported = true\n            if (supportedCredential.credential_subject_issuance) {\n              subjectIssuance = { credential_subject_issuance: supportedCredential.credential_subject_issuance }\n            }\n          }\n        })\n\n        if (!typeSupported) {\n          console.log(`Not all credential types ${JSON.stringify(credentialTypes)} are present in metadata for ${this.getIssuer()}`)\n          // throw Error(`Not all credential types ${JSON.stringify(credentialTypes)} are supported by issuer ${this.getIssuer()}`);\n        }\n      } else if (metadata.credential_configurations_supported && typeof metadata.credential_configurations_supported === 'object') {\n        let typeSupported = false\n        Object.values(metadata.credential_configurations_supported).forEach((supportedCredential) => {\n          const subTypes = getTypesFromCredentialSupported(supportedCredential)\n          if (\n            subTypes.every((t, i) => types[i] === t) ||\n            (types.length === 1 && (types[0] === supportedCredential.id || subTypes.includes(types[0])))\n          ) {\n            typeSupported = true\n          }\n        })\n\n        if (!typeSupported) {\n          throw Error(`Not all credential types ${JSON.stringify(credentialTypes)} are supported by issuer ${this.getIssuer()}`)\n        }\n      }\n      // todo: Format check? We might end up with some disjoint type / format combinations supported by the server\n    }\n    if (subjectIssuance) {\n      requestBuilder.withSubjectIssuance(subjectIssuance)\n    }\n\n    const credentialRequestClient = requestBuilder.build()\n\n    let proofBuilder: ProofOfPossessionBuilder<any> | undefined\n    if (proofCallbacks) {\n      proofBuilder = ProofOfPossessionBuilder.fromAccessTokenResponse({\n        accessTokenResponse: this.accessTokenResponse,\n        callbacks: proofCallbacks,\n        version: this.version(),\n      })\n        .withIssuer(this.getIssuer())\n        .withAlg(this.alg)\n\n      if (this._state.jwk) {\n        proofBuilder.withJWK(this._state.jwk)\n      }\n      if (this._state.kid) {\n        proofBuilder.withKid(this._state.kid)\n      }\n\n      if (this.clientId) {\n        proofBuilder.withClientId(this.clientId)\n      }\n      if (jti) {\n        proofBuilder.withJti(jti)\n      }\n    }\n    const request = proofBuilder\n      ? await credentialRequestClient.createCredentialRequest({\n          proofInput: proofBuilder,\n          credentialTypes,\n          context,\n          format,\n          version: this.version(),\n          credentialIdentifier,\n          subjectIssuance,\n        })\n      : await credentialRequestClient.createCredentialRequestWithoutProof({\n          credentialTypes,\n          context,\n          format,\n          version: this.version(),\n          credentialIdentifier,\n          subjectIssuance,\n        })\n    const response = await credentialRequestClient.acquireCredentialsUsingRequest(request, createDPoPOpts)\n    this._state.dpopResponseParams = response.params\n    if (response.errorBody) {\n      logger.debug(`Credential request error:\\r\\n${JSON.stringify(response.errorBody)}`)\n      throw Error(\n        `Retrieving a credential from ${this._state.endpointMetadata?.credential_endpoint} for issuer ${this.getIssuer()} failed with status: ${\n          response.origResponse.status\n        }`,\n      )\n    } else if (!response.successBody) {\n      logger.debug(`Credential request error. No success body`)\n      throw Error(\n        `Retrieving a credential from ${\n          this._state.endpointMetadata?.credential_endpoint\n        } for issuer ${this.getIssuer()} failed as there was no success response body`,\n      )\n    }\n    return { ...response.successBody, ...(this.dpopResponseParams && { params: this.dpopResponseParams }), access_token: response.access_token }\n  }\n\n  public async exportState(): Promise<string> {\n    return JSON.stringify(this._state)\n  }\n\n  getCredentialsSupported(\n    format?: (OID4VCICredentialFormat | string) | (OID4VCICredentialFormat | string)[],\n  ): Record<string, CredentialConfigurationSupportedV1_0_13> {\n    return getSupportedCredentials({\n      issuerMetadata: this.endpointMetadata.credentialIssuerMetadata,\n      version: this.version(),\n      format: format,\n      types: undefined,\n    }) as Record<string, CredentialConfigurationSupportedV1_0_13>\n  }\n\n  public async sendNotification(\n    credentialRequestOpts: Partial<CredentialRequestOpts>,\n    request: NotificationRequest,\n    accessToken?: string,\n  ): Promise<NotificationResponseResult> {\n    return sendNotification(credentialRequestOpts, request, accessToken ?? this._state.accessToken ?? this._state.accessTokenResponse?.access_token)\n  }\n\n  /* getCredentialOfferTypes(): string[][] {\n    if (!this.credentialOffer) {\n      return [];\n    } else if (this.credentialOffer.version < OpenId4VCIVersion.VER_1_0_11) {\n      const orig = this.credentialOffer.original_credential_offer as CredentialOfferPayloadV1_0_08;\n      const types: string[] = typeof orig.credential_type === 'string' ? [orig.credential_type] : orig.credential_type;\n      const result: string[][] = [];\n      result[0] = types;\n      return result;\n    } else {\n      return this.credentialOffer.credential_offer.credentials.map((c) => {\n        if (typeof c === 'string') {\n          return [c];\n        } else if ('types' in c) {\n          return c.types;\n        } else if ('vct' in c) {\n          return [c.vct];\n        } else {\n          return c.credential_definition.types;\n        }\n      });\n    }\n  }*/\n\n  issuerSupportedFlowTypes(): AuthzFlowType[] {\n    return (\n      this.credentialOffer?.supportedFlows ??\n      (this._state.endpointMetadata?.credentialIssuerMetadata?.authorization_endpoint ? [AuthzFlowType.AUTHORIZATION_CODE_FLOW] : [])\n    )\n  }\n\n  isFlowTypeSupported(flowType: AuthzFlowType): boolean {\n    return this.issuerSupportedFlowTypes().includes(flowType)\n  }\n\n  public hasAuthorizationURL(): boolean {\n    return !!this.authorizationURL\n  }\n\n  get authorizationURL(): string | undefined {\n    return this._state.authorizationURL\n  }\n\n  get credentialOffer(): CredentialOfferRequestWithBaseUrl | undefined {\n    return this._state.credentialOffer\n  }\n\n  public version(): OpenId4VCIVersion {\n    return this.credentialOffer?.version ?? OpenId4VCIVersion.VER_1_0_13\n  }\n\n  public get endpointMetadata(): EndpointMetadataResultV1_0_13 {\n    this.assertServerMetadata()\n    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n    return this._state.endpointMetadata!\n  }\n\n  get kid(): string {\n    this.assertIssuerData()\n    if (!this._state.kid) {\n      throw new Error('No value for kid is supplied')\n    }\n    return this._state.kid\n  }\n\n  get alg(): string {\n    this.assertIssuerData()\n    if (!this._state.alg) {\n      throw new Error('No value for alg is supplied')\n    }\n    return this._state.alg\n  }\n\n  set clientId(value: string | undefined) {\n    this._state.clientId = value\n  }\n\n  get clientId(): string | undefined {\n    return this._state.clientId\n  }\n\n  public hasAccessTokenResponse(): boolean {\n    return !!this._state.accessTokenResponse\n  }\n\n  get accessTokenResponse(): AccessTokenResponse {\n    this.assertAccessToken()\n    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n    return this._state.accessTokenResponse!\n  }\n\n  get dpopResponseParams(): DPoPResponseParams | undefined {\n    return this._state.dpopResponseParams\n  }\n\n  public getIssuer(): string {\n    this.assertIssuerData()\n    return this._state.credentialIssuer\n  }\n\n  public getAccessTokenEndpoint(): string {\n    this.assertIssuerData()\n    return this.endpointMetadata\n      ? this.endpointMetadata.token_endpoint\n      : AccessTokenClient.determineTokenURL({ issuerOpts: { issuer: this.getIssuer() } })\n  }\n\n  public getCredentialEndpoint(): string {\n    this.assertIssuerData()\n    return this.endpointMetadata ? this.endpointMetadata.credential_endpoint : `${this.getIssuer()}/credential`\n  }\n\n  public hasDeferredCredentialEndpoint(): boolean {\n    return !!this.getAccessTokenEndpoint()\n  }\n\n  public getDeferredCredentialEndpoint(): string {\n    this.assertIssuerData()\n    return this.endpointMetadata ? this.endpointMetadata.credential_endpoint : `${this.getIssuer()}/credential`\n  }\n\n  /**\n   * Too bad we need a method like this, but EBSI is not exposing metadata\n   */\n  public isEBSI(): boolean {\n    const credentialOffer = this.credentialOffer?.credential_offer as CredentialOfferPayloadV1_0_13\n\n    if (credentialOffer?.credential_configuration_ids) {\n      const credentialConfigurations = this.endpointMetadata.credentialIssuerMetadata?.credential_configurations_supported\n\n      if (credentialConfigurations) {\n        const isEBSITrustFramework = credentialOffer.credential_configuration_ids\n          .map((id) => credentialConfigurations[id])\n          .filter(\n            (config): config is CredentialConfigurationSupportedV1_0_13 =>\n              // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n              // @ts-ignore\n              config !== undefined && 'trust_framework' in config && 'name' in config.trust_framework,\n          )\n          // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n          // @ts-ignore\n          .some((config) => config.trust_framework.name.includes('ebsi'))\n\n        if (isEBSITrustFramework) {\n          return true\n        }\n      }\n    }\n\n    return (\n      this.clientId?.includes('ebsi') ||\n      this._state.kid?.includes('did:ebsi:') ||\n      this.getIssuer().includes('ebsi') ||\n      this.endpointMetadata.credentialIssuerMetadata?.authorization_endpoint?.includes('ebsi.eu') ||\n      this.endpointMetadata.credentialIssuerMetadata?.authorization_server?.includes('ebsi.eu')\n    )\n  }\n\n  private assertIssuerData(): void {\n    if (!this._state.credentialIssuer) {\n      throw Error(`No credential issuer value present`)\n    } else if (!this._state.credentialOffer && this._state.endpointMetadata && this.issuerSupportedFlowTypes().length === 0) {\n      throw Error(`No issuance initiation or credential offer present`)\n    }\n  }\n\n  private assertServerMetadata(): void {\n    if (!this._state.endpointMetadata) {\n      throw Error('No server metadata')\n    }\n  }\n\n  private assertAccessToken(): void {\n    if (!this._state.accessTokenResponse) {\n      throw Error(`No access token present`)\n    }\n  }\n\n  private syncAuthorizationRequestOpts(opts?: AuthorizationRequestOpts): AuthorizationRequestOpts {\n    let authorizationRequestOpts = { ...this._state?.authorizationRequestOpts, ...opts } as AuthorizationRequestOpts\n    if (!authorizationRequestOpts) {\n      // We only set a redirectUri if no options are provided.\n      // Note that this only works for mobile apps, that can handle a code query param on the default openid-credential-offer deeplink.\n      // Provide your own options if that is not desired!\n      authorizationRequestOpts = { redirectUri: `${DefaultURISchemes.CREDENTIAL_OFFER}://` }\n    }\n    const clientId = authorizationRequestOpts.clientId ?? this._state.clientId\n    // sync clientId\n    this._state.clientId = clientId\n    authorizationRequestOpts.clientId = clientId\n    return authorizationRequestOpts\n  }\n\n  private getAuthorizationCode = (\n    authorizationResponse?: string | AuthorizationResponse | AuthorizationChallengeCodeResponse,\n    code?: string,\n  ): string | undefined => {\n    if (authorizationResponse) {\n      this._state.authorizationCodeResponse = { ...toAuthorizationResponsePayload(authorizationResponse) }\n    } else if (code) {\n      this._state.authorizationCodeResponse = { code }\n    }\n\n    return (\n      (this._state.authorizationCodeResponse as AuthorizationResponse)?.code ??\n      (this._state.authorizationCodeResponse as AuthorizationChallengeCodeResponse)?.authorization_code\n    )\n  }\n}\n","import { CreateDPoPClientOpts, JWK } from '@sphereon/oid4vc-common'\nimport {\n  AccessTokenRequestOpts,\n  AccessTokenResponse,\n  Alg,\n  AuthorizationChallengeCodeResponse,\n  AuthorizationChallengeErrorResponse,\n  AuthorizationChallengeRequestOpts,\n  AuthorizationRequestOpts,\n  AuthorizationResponse,\n  AuthorizationServerOpts,\n  AuthzFlowType,\n  CodeChallengeMethod,\n  CredentialConfigurationSupported,\n  CredentialOfferPayloadV1_0_08,\n  CredentialOfferPayloadV1_0_11,\n  CredentialOfferRequestWithBaseUrl,\n  CredentialResponse,\n  CredentialsSupportedLegacy,\n  DefaultURISchemes,\n  DPoPResponseParams,\n  EndpointMetadataResultV1_0_11,\n  getClientIdFromCredentialOfferPayload,\n  getIssuerFromCredentialOfferPayload,\n  getSupportedCredentials,\n  getTypesFromCredentialSupported,\n  getTypesFromObject,\n  KID_JWK_X5C_ERROR,\n  OID4VCICredentialFormat,\n  OpenId4VCIVersion,\n  PKCEOpts,\n  ProofOfPossessionCallbacks,\n  toAuthorizationResponsePayload,\n} from '@sphereon/oid4vci-common'\nimport { CredentialFormat, Loggers } from '@sphereon/ssi-types'\n\nimport { AccessTokenClientV1_0_11 } from './AccessTokenClientV1_0_11'\nimport { acquireAuthorizationChallengeAuthCode } from './AuthorizationCodeClient'\nimport { createAuthorizationRequestUrlV1_0_11 } from './AuthorizationCodeClientV1_0_11'\nimport { CredentialOfferClientV1_0_11 } from './CredentialOfferClientV1_0_11'\nimport { CredentialRequestClientBuilderV1_0_11 } from './CredentialRequestClientBuilderV1_0_11'\nimport { MetadataClientV1_0_11 } from './MetadataClientV1_0_11'\nimport { ProofOfPossessionBuilder } from './ProofOfPossessionBuilder'\nimport { generateMissingPKCEOpts } from './functions'\n\nconst logger = Loggers.DEFAULT.get('sphereon:oid4vci')\n\nexport interface OpenID4VCIClientStateV1_0_11 {\n  credentialIssuer: string\n  credentialOffer?: CredentialOfferRequestWithBaseUrl\n  clientId?: string\n  kid?: string\n  jwk?: JWK\n  alg?: Alg | string\n  endpointMetadata?: EndpointMetadataResultV1_0_11\n  accessTokenResponse?: AccessTokenResponse\n  dpopResponseParams?: DPoPResponseParams\n  authorizationRequestOpts?: AuthorizationRequestOpts\n  authorizationCodeResponse?: AuthorizationResponse | AuthorizationChallengeCodeResponse\n  pkce: PKCEOpts\n  accessToken?: string\n  authorizationURL?: string\n}\n\nexport class OpenID4VCIClientV1_0_11 {\n  private readonly _state: OpenID4VCIClientStateV1_0_11\n\n  private constructor({\n    credentialOffer,\n    clientId,\n    kid,\n    alg,\n    credentialIssuer,\n    pkce,\n    authorizationRequest,\n    jwk,\n    endpointMetadata,\n    accessTokenResponse,\n    authorizationRequestOpts,\n    authorizationCodeResponse,\n    authorizationURL,\n  }: {\n    credentialOffer?: CredentialOfferRequestWithBaseUrl\n    kid?: string\n    alg?: Alg | string\n    clientId?: string\n    credentialIssuer?: string\n    pkce?: PKCEOpts\n    authorizationRequest?: AuthorizationRequestOpts // Can be provided here, or when manually calling createAuthorizationUrl\n    jwk?: JWK\n    endpointMetadata?: EndpointMetadataResultV1_0_11\n    accessTokenResponse?: AccessTokenResponse\n    authorizationRequestOpts?: AuthorizationRequestOpts\n    authorizationCodeResponse?: AuthorizationResponse | AuthorizationChallengeCodeResponse\n    authorizationURL?: string\n  }) {\n    const issuer = credentialIssuer ?? (credentialOffer ? getIssuerFromCredentialOfferPayload(credentialOffer.credential_offer) : undefined)\n    if (!issuer) {\n      throw Error('No credential issuer supplied or deduced from offer')\n    }\n    this._state = {\n      credentialOffer,\n      credentialIssuer: issuer,\n      kid,\n      alg,\n      // TODO: We need to refactor this and always explicitly call createAuthorizationRequestUrl, so we can have a credential selection first and use the kid as a default for the client id\n      clientId: clientId ?? (credentialOffer && getClientIdFromCredentialOfferPayload(credentialOffer.credential_offer)) ?? kid?.split('#')[0],\n      pkce: { disabled: false, codeChallengeMethod: CodeChallengeMethod.S256, ...pkce },\n      authorizationRequestOpts,\n      authorizationCodeResponse,\n      jwk,\n      endpointMetadata,\n      accessTokenResponse,\n      authorizationURL,\n    }\n    // Running syncAuthorizationRequestOpts later as it is using the state\n    if (!this._state.authorizationRequestOpts) {\n      this._state.authorizationRequestOpts = this.syncAuthorizationRequestOpts(authorizationRequest)\n    }\n    logger.debug(`Authorization req options: ${JSON.stringify(this._state.authorizationRequestOpts, null, 2)}`)\n  }\n\n  public static async fromCredentialIssuer({\n    kid,\n    alg,\n    retrieveServerMetadata,\n    clientId,\n    credentialIssuer,\n    pkce,\n    authorizationRequest,\n    createAuthorizationRequestURL,\n  }: {\n    credentialIssuer: string\n    kid?: string\n    alg?: Alg | string\n    retrieveServerMetadata?: boolean\n    clientId?: string\n    createAuthorizationRequestURL?: boolean\n    authorizationRequest?: AuthorizationRequestOpts // Can be provided here, or when manually calling createAuthorizationUrl\n    pkce?: PKCEOpts\n  }) {\n    const client = new OpenID4VCIClientV1_0_11({\n      kid,\n      alg,\n      clientId: clientId ?? authorizationRequest?.clientId,\n      credentialIssuer,\n      pkce,\n      authorizationRequest,\n    })\n    if (retrieveServerMetadata === undefined || retrieveServerMetadata) {\n      await client.retrieveServerMetadata()\n    }\n    if (createAuthorizationRequestURL === undefined || createAuthorizationRequestURL) {\n      await client.createAuthorizationRequestUrl({ authorizationRequest, pkce })\n    }\n    return client\n  }\n\n  public static async fromState({ state }: { state: OpenID4VCIClientStateV1_0_11 | string }): Promise<OpenID4VCIClientV1_0_11> {\n    const clientState = typeof state === 'string' ? JSON.parse(state) : state\n\n    return new OpenID4VCIClientV1_0_11(clientState)\n  }\n\n  public static async fromURI({\n    uri,\n    kid,\n    alg,\n    retrieveServerMetadata,\n    clientId,\n    pkce,\n    createAuthorizationRequestURL,\n    authorizationRequest,\n    resolveOfferUri,\n  }: {\n    uri: string\n    kid?: string\n    alg?: Alg | string\n    retrieveServerMetadata?: boolean\n    createAuthorizationRequestURL?: boolean\n    resolveOfferUri?: boolean\n    pkce?: PKCEOpts\n    clientId?: string\n    authorizationRequest?: AuthorizationRequestOpts // Can be provided here, or when manually calling createAuthorizationUrl\n  }): Promise<OpenID4VCIClientV1_0_11> {\n    const credentialOfferClient = await CredentialOfferClientV1_0_11.fromURI(uri, { resolve: resolveOfferUri })\n    const client = new OpenID4VCIClientV1_0_11({\n      credentialOffer: credentialOfferClient,\n      kid,\n      alg,\n      clientId: clientId ?? authorizationRequest?.clientId ?? credentialOfferClient.clientId,\n      pkce,\n      authorizationRequest,\n    })\n\n    if (retrieveServerMetadata === undefined || retrieveServerMetadata) {\n      await client.retrieveServerMetadata()\n    }\n    if (\n      credentialOfferClient.supportedFlows.includes(AuthzFlowType.AUTHORIZATION_CODE_FLOW) &&\n      (createAuthorizationRequestURL === undefined || createAuthorizationRequestURL)\n    ) {\n      await client.createAuthorizationRequestUrl({ authorizationRequest, pkce })\n      logger.debug(`Authorization Request URL: ${client._state.authorizationURL}`)\n    }\n\n    return client\n  }\n\n  /**\n   * Allows you to create an Authorization Request URL when using an Authorization Code flow. This URL needs to be accessed using the front channel (browser)\n   *\n   * The Identity provider would present a login screen typically; after you authenticated, it would redirect to the provided redirectUri; which can be same device or cross-device\n   * @param opts\n   */\n  public async createAuthorizationRequestUrl(opts?: { authorizationRequest?: AuthorizationRequestOpts; pkce?: PKCEOpts }): Promise<string> {\n    if (!this._state.authorizationURL) {\n      this.calculatePKCEOpts(opts?.pkce)\n      this._state.authorizationRequestOpts = this.syncAuthorizationRequestOpts(opts?.authorizationRequest)\n      if (!this._state.authorizationRequestOpts) {\n        throw Error(`No Authorization Request options present or provided in this call`)\n      }\n\n      // todo: Probably can go with current logic in MetadataClientV1_0_13 who will always set the authorization_endpoint when found\n      //  handling this because of the support for v1_0-08\n      if (\n        this._state.endpointMetadata?.credentialIssuerMetadata &&\n        'authorization_endpoint' in this._state.endpointMetadata.credentialIssuerMetadata\n      ) {\n        this._state.endpointMetadata.authorization_endpoint = this._state.endpointMetadata.credentialIssuerMetadata.authorization_endpoint as string\n      }\n      this._state.authorizationURL = await createAuthorizationRequestUrlV1_0_11({\n        pkce: this._state.pkce,\n        endpointMetadata: this.endpointMetadata,\n        authorizationRequest: this._state.authorizationRequestOpts,\n        credentialOffer: this.credentialOffer,\n        credentialsSupported: Object.values(this.getCredentialsSupported()) as CredentialsSupportedLegacy[],\n      })\n    }\n    return this._state.authorizationURL\n  }\n\n  public async retrieveServerMetadata(): Promise<EndpointMetadataResultV1_0_11> {\n    this.assertIssuerData()\n    if (!this._state.endpointMetadata) {\n      if (this.credentialOffer) {\n        this._state.endpointMetadata = await MetadataClientV1_0_11.retrieveAllMetadataFromCredentialOffer(this.credentialOffer)\n      } else if (this._state.credentialIssuer) {\n        this._state.endpointMetadata = await MetadataClientV1_0_11.retrieveAllMetadata(this._state.credentialIssuer)\n      } else {\n        throw Error(`Cannot retrieve issuer metadata without either a credential offer, or issuer value`)\n      }\n    }\n\n    return this.endpointMetadata\n  }\n\n  private calculatePKCEOpts(pkce?: PKCEOpts) {\n    this._state.pkce = generateMissingPKCEOpts({ ...this._state.pkce, ...pkce })\n  }\n\n  public async acquireAuthorizationChallengeCode(opts?: AuthorizationChallengeRequestOpts): Promise<AuthorizationChallengeCodeResponse> {\n    const response = await acquireAuthorizationChallengeAuthCode({\n      metadata: this.endpointMetadata,\n      credentialIssuer: this.getIssuer(),\n      clientId: this._state.clientId ?? this._state.authorizationRequestOpts?.clientId,\n      ...opts,\n    })\n\n    if (response.errorBody) {\n      logger.debug(`Authorization code error:\\r\\n${JSON.stringify(response.errorBody)}`)\n      const error = response.errorBody as AuthorizationChallengeErrorResponse\n      return Promise.reject(error)\n    } else if (!response.successBody) {\n      logger.debug(`Authorization code error. No success body`)\n      return Promise.reject(\n        Error(\n          `Retrieving an authorization code token from ${this._state.endpointMetadata?.authorization_challenge_endpoint} for issuer ${this.getIssuer()} failed as there was no success response body`,\n        ),\n      )\n    }\n\n    return { ...response.successBody }\n  }\n\n  public async acquireAccessToken(\n    opts?: Omit<AccessTokenRequestOpts, 'credentialOffer' | 'credentialIssuer' | 'metadata' | 'additionalParams'> & {\n      clientId?: string\n      authorizationResponse?: string | AuthorizationResponse | AuthorizationChallengeCodeResponse // Pass in an auth response, either as URI/redirect, or object\n      additionalRequestParams?: Record<string, any>\n    },\n  ): Promise<AccessTokenResponse & { params?: DPoPResponseParams }> {\n    const { pin, clientId = this._state.clientId ?? this._state.authorizationRequestOpts?.clientId } = opts ?? {}\n    let { redirectUri } = opts ?? {}\n\n    const code = this.getAuthorizationCode(opts?.authorizationResponse, opts?.code)\n\n    if (opts?.codeVerifier) {\n      this._state.pkce.codeVerifier = opts.codeVerifier\n    }\n    this.assertIssuerData()\n\n    const asOpts: AuthorizationServerOpts = { ...opts?.asOpts }\n    if (clientId) {\n      this._state.clientId = clientId\n      if (!asOpts.clientOpts) {\n        asOpts.clientOpts = { clientId }\n      }\n      asOpts.clientOpts.clientId = clientId\n    }\n    if (!this._state.accessTokenResponse) {\n      const accessTokenClient = new AccessTokenClientV1_0_11()\n\n      if (redirectUri && redirectUri !== this._state.authorizationRequestOpts?.redirectUri) {\n        console.log(\n          `Redirect URI mismatch between access-token (${redirectUri}) and authorization request (${this._state.authorizationRequestOpts?.redirectUri}). According to the specification that is not allowed.`,\n        )\n      }\n      if (this._state.authorizationRequestOpts?.redirectUri && !redirectUri) {\n        redirectUri = this._state.authorizationRequestOpts.redirectUri\n      }\n\n      const kid = asOpts.clientOpts?.kid ?? this._state.kid ?? this._state.authorizationRequestOpts?.requestObjectOpts?.kid\n      const clientAssertionType =\n        asOpts.clientOpts?.clientAssertionType ??\n        (kid && clientId && typeof asOpts.clientOpts?.signCallbacks?.signCallback === 'function'\n          ? 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'\n          : undefined)\n      if (this.isEBSI() || (clientId && kid)) {\n        if (!clientId) {\n          throw Error(`Client id expected for EBSI`)\n        }\n        asOpts.clientOpts = {\n          ...asOpts.clientOpts,\n          clientId,\n          ...(kid && { kid }),\n          ...(clientAssertionType && { clientAssertionType }),\n          signCallbacks: asOpts.clientOpts?.signCallbacks ?? this._state.authorizationRequestOpts?.requestObjectOpts?.signCallbacks,\n        }\n      }\n\n      const response = await accessTokenClient.acquireAccessToken({\n        credentialOffer: this.credentialOffer,\n        metadata: this.endpointMetadata,\n        credentialIssuer: this.getIssuer(),\n        pin,\n        ...(!this._state.pkce.disabled && { codeVerifier: this._state.pkce.codeVerifier }),\n        code,\n        redirectUri,\n        asOpts,\n        ...(opts?.createDPoPOpts && { createDPoPOpts: opts.createDPoPOpts }),\n        ...(opts?.additionalRequestParams && { additionalParams: opts.additionalRequestParams }),\n      })\n\n      if (response.errorBody) {\n        logger.debug(`Access token error:\\r\\n${JSON.stringify(response.errorBody)}`)\n        throw Error(\n          `Retrieving an access token from ${this._state.endpointMetadata?.token_endpoint} for issuer ${this.getIssuer()} failed with status: ${\n            response.origResponse.status\n          }`,\n        )\n      } else if (!response.successBody) {\n        logger.debug(`Access token error. No success body`)\n        throw Error(\n          `Retrieving an access token from ${\n            this._state.endpointMetadata?.token_endpoint\n          } for issuer ${this.getIssuer()} failed as there was no success response body`,\n        )\n      }\n      this._state.accessTokenResponse = response.successBody\n      this._state.dpopResponseParams = response.params\n      this._state.accessToken = response.successBody.access_token\n    }\n\n    return { ...this.accessTokenResponse, ...(this.dpopResponseParams && { params: this.dpopResponseParams }) }\n  }\n\n  public async acquireCredentials({\n    credentialTypes,\n    context,\n    proofCallbacks,\n    format,\n    kid,\n    jwk,\n    alg,\n    jti,\n    deferredCredentialAwait,\n    deferredCredentialIntervalInMS,\n    createDPoPOpts,\n  }: {\n    credentialTypes: string | string[]\n    context?: string[]\n    proofCallbacks: ProofOfPossessionCallbacks\n    format?: CredentialFormat | OID4VCICredentialFormat\n    kid?: string\n    jwk?: JWK\n    alg?: Alg | string\n    jti?: string\n    deferredCredentialAwait?: boolean\n    deferredCredentialIntervalInMS?: number\n    createDPoPOpts?: CreateDPoPClientOpts\n  }): Promise<CredentialResponse> {\n    if ([jwk, kid].filter((v) => v !== undefined).length > 1) {\n      throw new Error(KID_JWK_X5C_ERROR + `. jwk: ${jwk !== undefined}, kid: ${kid !== undefined}`)\n    }\n\n    if (alg) this._state.alg = alg\n    if (jwk) this._state.jwk = jwk\n    if (kid) this._state.kid = kid\n\n    const requestBuilder = this.credentialOffer\n      ? CredentialRequestClientBuilderV1_0_11.fromCredentialOffer({\n          credentialOffer: this.credentialOffer,\n          metadata: this.endpointMetadata,\n        })\n      : CredentialRequestClientBuilderV1_0_11.fromCredentialIssuer({\n          credentialIssuer: this.getIssuer(),\n          credentialTypes,\n          metadata: this.endpointMetadata,\n          version: this.version(),\n        })\n\n    requestBuilder.withTokenFromResponse(this.accessTokenResponse)\n    requestBuilder.withDeferredCredentialAwait(deferredCredentialAwait ?? false, deferredCredentialIntervalInMS)\n    if (this.endpointMetadata?.credentialIssuerMetadata) {\n      const metadata = this.endpointMetadata.credentialIssuerMetadata\n      const types = Array.isArray(credentialTypes) ? credentialTypes : [credentialTypes]\n\n      if (metadata.credentials_supported && Array.isArray(metadata.credentials_supported)) {\n        let typeSupported = false\n\n        metadata.credentials_supported.forEach((supportedCredential) => {\n          const subTypes = getTypesFromCredentialSupported(supportedCredential)\n          if (\n            subTypes.every((t, i) => types[i] === t) ||\n            (types.length === 1 && (types[0] === supportedCredential.id || subTypes.includes(types[0])))\n          ) {\n            typeSupported = true\n          }\n        })\n\n        if (!typeSupported) {\n          console.log(`Not all credential types ${JSON.stringify(credentialTypes)} are present in metadata for ${this.getIssuer()}`)\n          // throw Error(`Not all credential types ${JSON.stringify(credentialTypes)} are supported by issuer ${this.getIssuer()}`);\n        }\n      } else if (metadata.credentials_supported && !Array.isArray(metadata.credentials_supported)) {\n        const credentialsSupported = metadata.credentials_supported\n        if (types.some((type) => !metadata.credentials_supported || !credentialsSupported[type])) {\n          throw Error(`Not all credential types ${JSON.stringify(credentialTypes)} are supported by issuer ${this.getIssuer()}`)\n        }\n      }\n      // todo: Format check? We might end up with some disjoint type / format combinations supported by the server\n    }\n    const credentialRequestClient = requestBuilder.build()\n    const proofBuilder = ProofOfPossessionBuilder.fromAccessTokenResponse({\n      accessTokenResponse: this.accessTokenResponse,\n      callbacks: proofCallbacks,\n      version: this.version(),\n    })\n      .withIssuer(this.getIssuer())\n      .withAlg(this.alg)\n\n    if (this._state.jwk) {\n      proofBuilder.withJWK(this._state.jwk)\n    }\n    if (this._state.kid) {\n      proofBuilder.withKid(this._state.kid)\n    }\n\n    if (this.clientId) {\n      proofBuilder.withClientId(this.clientId)\n    }\n    if (jti) {\n      proofBuilder.withJti(jti)\n    }\n    const response = await credentialRequestClient.acquireCredentialsUsingProof({\n      proofInput: proofBuilder,\n      credentialTypes,\n      context,\n      format,\n      createDPoPOpts,\n    })\n    this._state.dpopResponseParams = response.params\n    if (response.errorBody) {\n      logger.debug(`Credential request error:\\r\\n${JSON.stringify(response.errorBody)}`)\n      throw Error(\n        `Retrieving a credential from ${this._state.endpointMetadata?.credential_endpoint} for issuer ${this.getIssuer()} failed with status: ${\n          response.origResponse.status\n        }`,\n      )\n    } else if (!response.successBody) {\n      logger.debug(`Credential request error. No success body`)\n      throw Error(\n        `Retrieving a credential from ${\n          this._state.endpointMetadata?.credential_endpoint\n        } for issuer ${this.getIssuer()} failed as there was no success response body`,\n      )\n    }\n    return { ...response.successBody, ...(this.dpopResponseParams && { params: this.dpopResponseParams }) }\n  }\n\n  public async exportState(): Promise<string> {\n    return JSON.stringify(this._state)\n  }\n\n  // FIXME: We really should convert <v11 to v12 objects first. Right now the logic doesn't map nicely and is brittle.\n  // We should resolve IDs to objects first in case of strings.\n  // When < v11 convert into a v12 object. When v12 object retain it.\n  // Then match the object array on server metadata\n  getCredentialsSupportedV11(\n    restrictToInitiationTypes: boolean,\n    format?: (OID4VCICredentialFormat | string) | (OID4VCICredentialFormat | string)[],\n  ): Record<string, CredentialConfigurationSupported> {\n    return getSupportedCredentials({\n      issuerMetadata: this.endpointMetadata.credentialIssuerMetadata,\n      version: this.version(),\n      format: format,\n      types: restrictToInitiationTypes ? this.getCredentialOfferTypes() : undefined,\n    }) as Record<string, CredentialConfigurationSupported>\n  }\n\n  getCredentialsSupported(format?: (OID4VCICredentialFormat | string) | (OID4VCICredentialFormat | string)[]): CredentialConfigurationSupported[] {\n    return getSupportedCredentials({\n      issuerMetadata: this.endpointMetadata.credentialIssuerMetadata,\n      version: this.version(),\n      format: format,\n      types: undefined,\n    }) as CredentialConfigurationSupported[]\n  }\n\n  getCredentialOfferTypes(): string[][] {\n    if (!this.credentialOffer) {\n      return []\n    } else if (this.credentialOffer.version < OpenId4VCIVersion.VER_1_0_11) {\n      const orig = this.credentialOffer.original_credential_offer as CredentialOfferPayloadV1_0_08\n      const types: string[] = typeof orig.credential_type === 'string' ? [orig.credential_type] : orig.credential_type\n      const result: string[][] = []\n      result[0] = types\n      return result\n    } else if (this.credentialOffer.version < OpenId4VCIVersion.VER_1_0_13) {\n      return (this.credentialOffer.credential_offer as CredentialOfferPayloadV1_0_11).credentials.map((c) => getTypesFromObject(c) ?? [])\n    }\n    // we don't support > V11\n    throw Error(`This class only supports version 11 and lower! Version: ${this.version()}`)\n  }\n\n  issuerSupportedFlowTypes(): AuthzFlowType[] {\n    return (\n      this.credentialOffer?.supportedFlows ??\n      (this._state.endpointMetadata?.credentialIssuerMetadata?.authorization_endpoint ? [AuthzFlowType.AUTHORIZATION_CODE_FLOW] : [])\n    )\n  }\n\n  isFlowTypeSupported(flowType: AuthzFlowType): boolean {\n    return this.issuerSupportedFlowTypes().includes(flowType)\n  }\n\n  get authorizationURL(): string | undefined {\n    return this._state.authorizationURL\n  }\n\n  public hasAuthorizationURL(): boolean {\n    return !!this.authorizationURL\n  }\n\n  get credentialOffer(): CredentialOfferRequestWithBaseUrl | undefined {\n    return this._state.credentialOffer\n  }\n\n  public version(): OpenId4VCIVersion {\n    return this.credentialOffer?.version ?? OpenId4VCIVersion.VER_1_0_11\n  }\n\n  public get endpointMetadata(): EndpointMetadataResultV1_0_11 {\n    this.assertServerMetadata()\n    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n    return this._state.endpointMetadata!\n  }\n\n  get kid(): string {\n    this.assertIssuerData()\n    if (!this._state.kid) {\n      throw new Error('No value for kid is supplied')\n    }\n    return this._state.kid\n  }\n\n  get alg(): string {\n    this.assertIssuerData()\n    if (!this._state.alg) {\n      throw new Error('No value for alg is supplied')\n    }\n    return this._state.alg\n  }\n\n  set clientId(value: string | undefined) {\n    this._state.clientId = value\n  }\n\n  get clientId(): string | undefined {\n    return this._state.clientId\n  }\n\n  public hasAccessTokenResponse(): boolean {\n    return !!this._state.accessTokenResponse\n  }\n\n  get accessTokenResponse(): AccessTokenResponse {\n    this.assertAccessToken()\n    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n    return this._state.accessTokenResponse!\n  }\n\n  get dpopResponseParams(): DPoPResponseParams | undefined {\n    return this._state.dpopResponseParams\n  }\n\n  public getIssuer(): string {\n    this.assertIssuerData()\n    return this._state.credentialIssuer\n  }\n\n  public getAccessTokenEndpoint(): string {\n    this.assertIssuerData()\n    return this.endpointMetadata\n      ? this.endpointMetadata.token_endpoint\n      : AccessTokenClientV1_0_11.determineTokenURL({ issuerOpts: { issuer: this.getIssuer() } })\n  }\n\n  public getCredentialEndpoint(): string {\n    this.assertIssuerData()\n    return this.endpointMetadata ? this.endpointMetadata.credential_endpoint : `${this.getIssuer()}/credential`\n  }\n\n  public hasDeferredCredentialEndpoint(): boolean {\n    return !!this.getAccessTokenEndpoint()\n  }\n\n  public getDeferredCredentialEndpoint(): string {\n    this.assertIssuerData()\n    return this.endpointMetadata ? this.endpointMetadata.credential_endpoint : `${this.getIssuer()}/credential`\n  }\n\n  /**\n   * Too bad we need a method like this, but EBSI is not exposing metadata\n   */\n  public isEBSI() {\n    if (\n      this.credentialOffer &&\n      (this.credentialOffer?.credential_offer as CredentialOfferPayloadV1_0_11)?.credentials?.find(\n        (cred) =>\n          // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n          // @ts-ignore\n          typeof cred !== 'string' && 'trust_framework' in cred && 'name' in cred.trust_framework && cred.trust_framework.name.includes('ebsi'),\n      )\n    ) {\n      return true\n    }\n    // this.assertIssuerData();\n    return (\n      this.clientId?.includes('ebsi') ||\n      this._state.kid?.includes('did:ebsi:') ||\n      this.getIssuer().includes('ebsi') ||\n      this.endpointMetadata.credentialIssuerMetadata?.authorization_endpoint?.includes('ebsi.eu') ||\n      this.endpointMetadata.credentialIssuerMetadata?.authorization_server?.includes('ebsi.eu')\n    )\n  }\n\n  private assertIssuerData(): void {\n    if (!this._state.credentialIssuer) {\n      throw Error(`No credential issuer value present`)\n    } else if (!this._state.credentialOffer && this._state.endpointMetadata && this.issuerSupportedFlowTypes().length === 0) {\n      throw Error(`No issuance initiation or credential offer present`)\n    }\n  }\n\n  private assertServerMetadata(): void {\n    if (!this._state.endpointMetadata) {\n      throw Error('No server metadata')\n    }\n  }\n\n  private assertAccessToken(): void {\n    if (!this._state.accessTokenResponse) {\n      throw Error(`No access token present`)\n    }\n  }\n\n  private syncAuthorizationRequestOpts(opts?: AuthorizationRequestOpts): AuthorizationRequestOpts {\n    let authorizationRequestOpts = { ...this._state?.authorizationRequestOpts, ...opts } as AuthorizationRequestOpts\n    if (!authorizationRequestOpts) {\n      // We only set a redirectUri if no options are provided.\n      // Note that this only works for mobile apps, that can handle a code query param on the default openid-credential-offer deeplink.\n      // Provide your own options if that is not desired!\n      authorizationRequestOpts = { redirectUri: `${DefaultURISchemes.CREDENTIAL_OFFER}://` }\n    }\n    const clientId = authorizationRequestOpts.clientId ?? this._state.clientId\n    // sync clientId\n    this._state.clientId = clientId\n    authorizationRequestOpts.clientId = clientId\n    return authorizationRequestOpts\n  }\n\n  private getAuthorizationCode = (\n    authorizationResponse?: string | AuthorizationResponse | AuthorizationChallengeCodeResponse,\n    code?: string,\n  ): string | undefined => {\n    if (authorizationResponse) {\n      this._state.authorizationCodeResponse = { ...toAuthorizationResponsePayload(authorizationResponse) }\n    } else if (code) {\n      this._state.authorizationCodeResponse = { code }\n    }\n\n    return (\n      (this._state.authorizationCodeResponse as AuthorizationResponse)?.code ??\n      (this._state.authorizationCodeResponse as AuthorizationChallengeCodeResponse)?.authorization_code\n    )\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;aAAAA;EAAA;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAC,0BAA4B;;;ACA5B,IAAAC,wBAAuE;AACvE,IAAAC,yBAsBO;AACP,IAAAC,oBAA4B;;;ACxB5B,IAAAC,yBAWO;AACP,IAAAC,oBAAwB;;;ACZxB,4BAAkH;AAE3G,IAAMC,0BAA0B,wBAACC,SA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yB;AAC/B,QAAI,CAAC,KAAKzD,OAAOK,kBAAkB;AACjC,YAAMa,MAAM,oCAAoC;IAClD,WAAW,CAAC,KAAKlB,OAAOC,mBAAmB,KAAKD,OAAOS,oBAAoB,KAAK6J,yBAAwB,EAAGvD,WAAW,GAAG;AACvH,YAAM7F,MAAM,oDAAoD;IAClE;EACF;EAEQwJ,uBAA6B;AACnC,QAAI,CAAC,KAAK1K,OAAOS,kBAAkB;AACjC,YAAMS,MAAM,oBAAA;IACd;EACF;EAEQ2J,oBAA0B;AAChC,QAAI,CAAC,KAAK7K,OAAOU,qBAAqB;AACpC,YAAMQ,MAAM,yBAAyB;IACvC;EACF;EAEQO,6BAA6BuB,MAA2D;AAC9F,QAAIrC,2BAA2B;MAAE,GAAG,KAAKX,QAAQW;MAA0B,GAAGqC;IAAK;AACnF,QAAI,CAACrC,0BAA0B;AAI7BA,iCAA2B;QAAEgE,aAAa,GAAG8G,0CAAkBC,gBAAgB;MAAM;IACvF;AACA,UAAMxL,WAAWS,yBAAyBT,YAAY,KAAKF,OAAOE;AAElE,SAAKF,OAAOE,WAAWA;AACvBS,6BAAyBT,WAAWA;AACpC,WAAOS;EACT;EAEQkE,uBAAuB,wBAC7BC,uBACAF,SAAAA;AAEA,QAAIE,uBAAuB;AACzB,WAAK9E,OAAOY,4BAA4B;QAAE,OAAG+K,wDAA+B7G,qBAAAA;MAAuB;IACrG,WAAWF,MAAM;AACf,WAAK5E,OAAOY,4BAA4B;QAAEgE;MAAK;IACjD;AAEA,WACG,KAAK5E,OAAOY,2BAAqDgE,QACjE,KAAK5E,OAAOY,2BAAkEgL;EAEnF,GAd+B;AAejC;;;A1B3sBO,IAAMC,OAA6BC,oCAAYC,IAAI,yBAAA;","names":["LOG","import_oid4vci_common","import_oid4vc_common","import_oid4vci_common","import_ssi_types","import_oid4vci_common","import_ssi_types","generateMissingPKCEOpts","pkce","disabled","codeChallengeMethod","CodeChallengeMethod","S256","codeVerifier","generateCodeVerifier","assertValidCodeVerifier","codeChallenge","createCodeChallenge","import_oid4vci_common","import_oid4vci_common","LOG","VCI_LOGGERS","options","methods","LogMethod","EVENT","DEBUG_PKG","get","sendNotification","credentialRequestOpts","request","accessToken","LOG","info","event","notification_id","notificationEndpoint","Error","token","response","post","JSON","stringify","bearerToken","error","errorBody","undefined","result","warning","debug","import_oid4vci_common","import_ssi_types","logger","Loggers","DEFAULT","get","retrieveWellknown","host","endpointType","opts","result","getJson","endsWith","slice","exceptionOnHttpErrorStatus","errorOnNotFound","origResponse","status","debug","statusText","import_oid4vci_common","import_oid4vci_common","ProofOfPossessionBuilder","proof","callbacks","version","mode","kid","jwk","aud","clientId","issuer","jwt","alg","jti","cNonce","typ","accessTokenResponse","withJwt","withTyp","OpenId4VCIVersion","VER_1_0_11","withAccessTokenResponse","manual","fromJwt","fromAccessTokenResponse","fromProof","withAud","withClientId","withKid","withJWK","withIssuer","withAlg","withJti","Error","withAccessTokenNonce","accessToken","c_nonce","withEndpointMetadata","endpointMetadata","NO_JWT_PROVIDED","header","payload","Array","isArray","iss","nonce","build","Promise","resolve","createProofOfPossession","PROOF_CANT_BE_CONSTRUCTED","createJwtBearerClientAssertion","request","opts","asOpts","credentialIssuer","clientOpts","clientAssertionType","clientId","client_id","signCallbacks","alg","kid","Promise","reject","Error","signCallback","startsWith","includes","split","jwt","header","typ","payload","iss","sub","aud","jti","uuidv4","exp","Math","floor","Date","now","iat","pop","ProofOfPossessionBuilder","fromJwt","callbacks","version","OpenId4VCIVersion","VER_1_0_13","mode","build","client_assertion_type","client_assertion","import_oid4vci_common","isUriEncoded","str","pattern","test","handleCredentialOfferUri","uri","uriObj","getURIComponentsAsArray","credentialOfferUri","decodeURIComponent","decodedUri","response","fetch","status","Promise","reject","statusText","headers","get","startsWith","credential_offer","decodeJsonProperties","json","constructBaseResponse","request","scheme","baseUrl","clientId","getClientIdFromCredentialOfferPayload","grants","authorization_code","issuer_state","issuerState","PRE_AUTH_GRANT_LITERAL","PRE_AUTH_CODE_LITERAL","preAuthorizedCode","tx_code","txCode","logger","Loggers","DEFAULT","get","MetadataClientV1_0_13","retrieveAllMetadataFromCredentialOffer","credentialOffer","retrieveAllMetadataFromCredentialOfferRequest","credential_offer","request","issuer","getIssuerFromCredentialOfferPayload","retrieveAllMetadata","Error","opts","token_endpoint","credential_endpoint","deferred_credential_endpoint","authorization_endpoint","authorization_challenge_endpoint","authorizationServerType","authorization_servers","oid4vciResponse","retrieveOpenID4VCIServerMetadata","errorOnNotFound","credentialIssuerMetadata","successBody","debug","JSON","stringify","response","retrieveWellknown","WellKnownEndpoints","OPENID_CONFIGURATION","authMetadata","OAUTH_AS","includes","console","warn","endsWith","authorization_server","authorizationServerMetadata","issuerHost","OPENID4VCI_ISSUER","undefined","import_oid4vc_common","shouldRetryTokenRequestWithDPoPNonce","response","errorBody","error","dpopTokenRequestNonceError","ok","dPoPNonce","origResponse","headers","get","Error","dpopNonce","shouldRetryResourceRequestWithDPoPNonce","status","wwwAuthenticateHeader","includes","AccessTokenClient","acquireAccessToken","opts","asOpts","pin","codeVerifier","code","redirectUri","metadata","createDPoPOpts","credentialOffer","assertedUniformCredentialOffer","undefined","pinMetadata","getPinMetadata","credential_offer","issuer","credentialIssuer","getIssuerFromCredentialOfferPayload","Error","issuerOpts","acquireAccessTokenUsingRequest","accessTokenRequest","createAccessTokenRequest","additionalParams","validate","requestTokenURL","determineTokenURL","fetchMetadata","MetadataClientV1_0_13","retrieveAllMetadata","errorOnNotFound","useDpop","dPoPSigningAlgValuesSupported","length","dPoP","createDPoP","getCreateDPoPOptions","response","sendAuthCode","headers","dpop","nextDPoPNonce","jwtPayloadProps","nonce","retryWithNonce","shouldRetryTokenRequestWithDPoPNonce","ok","dpopNonce","successDPoPNonce","origResponse","get","successBody","token_type","params","credentialOfferRequest","toUniformCredentialOfferRequest","request","clientOpts","clientId","client_id","credential_issuer","createJwtBearerClientAssertion","supportedFlows","includes","AuthzFlowType","AUTHORIZATION_CODE_FLOW","grant_type","GrantTypes","AUTHORIZATION_CODE","redirect_uri","code_verifier","PRE_AUTHORIZED_CODE_FLOW","assertAlphanumericPin","user_pin","tx_code","PRE_AUTHORIZED_CODE","PRE_AUTH_CODE_LITERAL","grants","PRE_AUTH_GRANT_LITERAL","assertPreAuthorizedGrantType","grantType","assertAuthorizationGrantType","requestPayload","TokenErrorResponse","invalid_request","grantDetails","isPinRequired","LOG","warning","txCode","pinMeta","regex","input_mode","RegExp","test","assertNonEmptyPreAuthorizedCode","assertNonEmptyCodeVerifier","assertNonEmptyCode","throwNotSupportedFlow","formPost","convertJsonToURI","mode","JsonURIMode","X_FORM_WWW_URLENCODED","customHeaders","token_endpoint","url","as","creatTokenURLFromURL","allowInsecureEndpoints","tokenEndpoint","ObjectUtils","isString","debug","startsWith","hostname","replace","endpoint","substring","scheme","split","import_oid4vc_common","import_oid4vci_common","import_ssi_types","logger","Loggers","DEFAULT","get","AccessTokenClientV1_0_11","acquireAccessToken","opts","asOpts","pin","codeVerifier","code","redirectUri","metadata","createDPoPOpts","credentialOffer","assertedUniformCredentialOffer","undefined","isPinRequired","isPinRequiredValue","credential_offer","issuer","credentialIssuer","getIssuerFromCredentialOfferPayload","Error","issuerOpts","acquireAccessTokenUsingRequest","accessTokenRequest","createAccessTokenRequest","additionalParams","pinMetadata","validate","requestTokenURL","determineTokenURL","fetchMetadata","MetadataClientV1_0_13","retrieveAllMetadata","errorOnNotFound","useDpop","dPoPSigningAlgValuesSupported","length","dPoP","createDPoP","getCreateDPoPOptions","response","sendAuthCode","headers","dpop","nextDPoPNonce","jwtPayloadProps","nonce","retryWithNonce","shouldRetryTokenRequestWithDPoPNonce","ok","dpopNonce","successDPoPNonce","origResponse","successBody","token_type","params","credentialOfferRequest","toUniformCredentialOfferRequest","request","credential_issuer","clientOpts","clientId","client_id","createJwtBearerClientAssertion","version","OpenId4VCIVersion","VER_1_0_11","supportedFlows","includes","AuthzFlowType","AUTHORIZATION_CODE_FLOW","grant_type","GrantTypes","AUTHORIZATION_CODE","redirect_uri","code_verifier","PRE_AUTHORIZED_CODE_FLOW","assertNumericPin","user_pin","PRE_AUTHORIZED_CODE","PRE_AUTH_CODE_LITERAL","grants","PRE_AUTH_GRANT_LITERAL","assertPreAuthorizedGrantType","grantType","assertAuthorizationGrantType","requestPayload","TokenErrorResponse","invalid_request","user_pin_required","debug","test","assertNonEmptyPreAuthorizedCode","assertNonEmptyCodeVerifier","assertNonEmptyCode","throwNotSupportedFlow","formPost","convertJsonToURI","mode","JsonURIMode","X_FORM_WWW_URLENCODED","customHeaders","token_endpoint","url","as","creatTokenURLFromURL","allowInsecureEndpoints","tokenEndpoint","ObjectUtils","isString","startsWith","hostname","replace","endpoint","substring","scheme","split","import_oid4vci_common","import_ssi_types","import_oid4vci_common","import_ssi_types","import_oid4vci_common","import_ssi_types","logger","Loggers","DEFAULT","get","MetadataClientV1_0_11","retrieveAllMetadataFromCredentialOffer","credentialOffer","retrieveAllMetadataFromCredentialOfferRequest","credential_offer","request","issuer","getIssuerFromCredentialOfferPayload","retrieveAllMetadata","Error","opts","token_endpoint","credential_endpoint","deferred_credential_endpoint","authorization_endpoint","authorization_challenge_endpoint","authorizationServerType","authorization_server","oid4vciResponse","retrieveOpenID4VCIServerMetadata","errorOnNotFound","credentialIssuerMetadata","successBody","debug","JSON","stringify","response","retrieveWellknown","WellKnownEndpoints","OPENID_CONFIGURATION","authMetadata","OAUTH_AS","console","warn","endsWith","authorizationServerMetadata","issuerHost","OPENID4VCI_ISSUER","undefined","logger","Loggers","DEFAULT","get","MetadataClient","retrieveAllMetadataFromCredentialOffer","credentialOffer","determineSpecVersionFromOffer","credential_offer","OpenId4VCIVersion","VER_1_0_13","MetadataClientV1_0_13","MetadataClientV1_0_11","retrieveAllMetadataFromCredentialOfferRequest","request","issuer","getIssuerFromCredentialOfferPayload","Error","retrieveAllMetadata","opts","token_endpoint","credential_endpoint","deferred_credential_endpoint","authorization_endpoint","authorization_challenge_endpoint","authorizationServerType","authorization_servers","authorization_server","undefined","oid4vciResponse","retrieveOpenID4VCIServerMetadata","errorOnNotFound","credentialIssuerMetadata","successBody","debug","JSON","stringify","response","retrieveWellknown","WellKnownEndpoints","OPENID_CONFIGURATION","authMetadata","OAUTH_AS","includes","console","warn","endsWith","authorizationServerMetadata","issuerHost","OPENID4VCI_ISSUER","logger","Loggers","DEFAULT","get","createSignedAuthRequestWhenNeeded","requestObject","opts","requestObjectMode","CreateRequestObjectMode","REQUEST_URI","Error","REQUEST_OBJECT","signCallbacks","signCallback","kid","client_metadata","clientMetadata","jwksUri","authorization_details","JSON","parse","aud","iss","client_id","jwt","header","alg","typ","payload","pop","ProofOfPossessionBuilder","fromJwt","callbacks","version","OpenId4VCIVersion","VER_1_0_11","mode","build","filterSupportedCredentials","credentialOffer","credentialsSupported","credential_configuration_ids","Object","entries","filter","entry","includes","map","configuration_id","createAuthorizationRequestUrl","pkce","endpointMetadata","authorizationRequest","credentialConfigurationSupported","clientId","removeDisplayAndValueTypes","obj","newObj","prop","redirectUri","requestObjectOpts","NONE","authorizationMetadata","authorizationServerMetadata","credentialIssuerMetadata","authorizationDetails","parMode","require_pushed_authorization_requests","PARMode","REQUIRE","AUTO","NEVER","scope","credential_offer","ver","determineSpecVersionFromOffer","VER_1_0_13","creds","flatMap","cred","locations","credential_issuer","issuer","credential_configuration_id","format","undefined","vct","doctype","credential_definition","isW3cCredentialSupported","type","credentialSubject","claims","length","authorization_endpoint","parEndpoint","pushed_authorization_request_endpoint","queryObj","response_type","ResponseType","AUTH_CODE","disabled","code_challenge_method","codeChallengeMethod","CodeChallengeMethod","S256","code_challenge","codeChallenge","stringify","handleAuthorizationDetails","redirect_uri","issuerState","issuer_state","state","debug","parResponse","formPost","convertJsonToURI","JsonURIMode","X_FORM_WWW_URLENCODED","uriTypeProperties","contentType","accept","errorBody","successBody","origResponse","statusText","request_uri","authorization_server","url","baseUrl","Array","isArray","value","handleLocations","push","acquireAuthorizationChallengeAuthCode","metadata","credentialIssuer","issuerOpts","acquireAuthorizationChallengeAuthCodeUsingRequest","authorizationChallengeRequest","createAuthorizationChallengeRequest","fetchMetadata","MetadataClient","retrieveAllMetadata","errorOnNotFound","authorizationChallengeCodeUrl","authorization_challenge_endpoint","Promise","reject","response","sendAuthorizationChallengeRequest","authSession","presentationDuringIssuanceSession","request","auth_session","presentation_during_issuance_session","customHeaders","headers","import_oid4vci_common","import_ssi_types","logger","Loggers","DEFAULT","get","createAuthorizationRequestUrlV1_0_11","pkce","endpointMetadata","authorizationRequest","credentialOffer","credentialsSupported","redirectUri","clientId","requestObjectOpts","requestObjectMode","CreateRequestObjectMode","NONE","scope","authorizationDetails","parMode","credentialIssuerMetadata","require_pushed_authorization_requests","PARMode","REQUIRE","AUTO","Error","creds","credential_offer","credentials","flatMap","cred","filter","map","type","locations","issuer","format","Array","isArray","length","authorization_endpoint","parEndpoint","pushed_authorization_request_endpoint","includes","s","join","queryObj","response_type","ResponseType","AUTH_CODE","disabled","code_challenge_method","codeChallengeMethod","CodeChallengeMethod","S256","code_challenge","codeChallenge","authorization_details","JSON","stringify","handleAuthorizationDetailsV1_0_11","redirect_uri","client_id","issuerState","issuer_state","NEVER","debug","parResponse","formPost","convertJsonToURI","mode","JsonURIMode","X_FORM_WWW_URLENCODED","uriTypeProperties","contentType","accept","errorBody","successBody","console","log","origResponse","statusText","request_uri","createSignedAuthRequestWhenNeeded","aud","authorization_server","url","baseUrl","value","handleLocations","push","import_oid4vc_common","import_oid4vci_common","import_ssi_types","logger","Loggers","DEFAULT","get","buildProof","proofInput","opts","cNonce","Error","ProofOfPossessionBuilder","fromProof","version","build","withAccessTokenNonce","CredentialRequestClient","_credentialRequestOpts","_isDeferred","credentialRequestOpts","isDeferred","getCredentialEndpoint","credentialEndpoint","getDeferredCredentialEndpoint","deferredCredentialEndpoint","builder","acquireCredentialsWithoutProof","credentialIdentifier","credentialTypes","format","context","subjectIssuance","request","createCredentialRequestWithoutProof","acquireCredentialsUsingRequestWithoutProof","createDPoPOpts","acquireCredentialsUsingProof","createCredentialRequest","acquireCredentialsUsingRequest","uniformRequest","acquireCredentialsUsingRequestImpl","OpenId4VCIVersion","VER_1_0_13","getCredentialRequestForVersion","isValidURL","debug","URL_NOT_VALID","JSON","stringify","requestToken","token","dPoP","createDPoP","getCreateDPoPOptions","accessToken","undefined","response","post","bearerToken","customHeaders","dpop","nextDPoPNonce","jwtPayloadProps","nonce","retryWithNonce","shouldRetryResourceRequestWithDPoPNonce","ok","dpopNonce","successDPoPNonce","origResponse","headers","isDeferredCredentialResponse","deferredCredentialAwait","successBody","acquireDeferredCredential","access_token","credential_subject_issuance","params","transactionId","transaction_id","acceptance_token","deferredCredentialIntervalInMS","createCredentialRequestImpl","credential_identifier","proof","formatSelection","getUniformFormat","typesSelection","length","types","Array","isArray","issuer_state","issuerState","credential_definition","type","VER_1_0_12","vct","doctype","import_oid4vci_common","CredentialOfferClient","fromURI","uri","opts","LOG","debug","includes","Error","scheme","split","baseUrl","version","determineSpecVersionFromURI","log","credentialOffer","credentialOfferPayload","OpenId4VCIVersion","VER_1_0_11","convertURIToJsonObject","arrayTypeProperties","requiredProperties","credential_offer","handleCredentialOfferUri","credential_offer_uri","undefined","request","toUniformCredentialOfferRequest","constructBaseResponse","userPinRequired","grants","PRE_AUTH_GRANT_LITERAL","user_pin_required","tx_code","toURI","requestWithBaseUrl","JSON","stringify","replace","param","isUri","valueOf","length","endsWith","convertJsonToURI","original_credential_offer","uriTypeProperties","VER_1_0_13","import_oid4vci_common","import_ssi_types","logger","Loggers","DEFAULT","get","CredentialOfferClientV1_0_11","fromURI","uri","opts","debug","includes","Error","scheme","split","baseUrl","version","determineSpecVersionFromURI","credentialOffer","credentialOfferPayload","OpenId4VCIVersion","VER_1_0_11","convertURIToJsonObject","arrayTypeProperties","requiredProperties","credential_offer","credential_offer_uri","undefined","request","toUniformCredentialOfferRequest","clientId","getClientIdFromCredentialOfferPayload","grants","authorization_code","issuer_state","issuerState","PRE_AUTH_GRANT_LITERAL","PRE_AUTH_CODE_LITERAL","preAuthorizedCode","userPinRequired","user_pin_required","toURI","requestWithBaseUrl","JSON","stringify","replace","param","isUri","valueOf","length","endsWith","convertJsonToURI","original_credential_offer","uriTypeProperties","import_oid4vci_common","import_ssi_types","logger","Loggers","DEFAULT","get","CredentialOfferClientV1_0_13","fromURI","uri","opts","debug","includes","Error","scheme","split","baseUrl","version","determineSpecVersionFromURI","credentialOffer","handleCredentialOfferUri","convertURIToJsonObject","arrayTypeProperties","requiredProperties","credential_offer_uri","undefined","credential_offer","request","toUniformCredentialOfferRequest","constructBaseResponse","userPinRequired","grants","PRE_AUTH_GRANT_LITERAL","tx_code","toURI","requestWithBaseUrl","JSON","stringify","replace","param","isUri","valueOf","OpenId4VCIVersion","VER_1_0_11","length","endsWith","convertJsonToURI","original_credential_offer","uriTypeProperties","VER_1_0_13","import_oid4vc_common","import_oid4vci_common","import_ssi_types","logger","Loggers","DEFAULT","get","CredentialRequestClientV1_0_11","_credentialRequestOpts","_isDeferred","credentialRequestOpts","isDeferred","getCredentialEndpoint","credentialEndpoint","getDeferredCredentialEndpoint","deferredCredentialEndpoint","builder","acquireCredentialsUsingProof","opts","credentialTypes","proofInput","format","context","request","createCredentialRequest","version","acquireCredentialsUsingRequest","createDPoPOpts","uniformRequest","getCredentialRequestForVersion","isValidURL","debug","Error","URL_NOT_VALID","JSON","stringify","requestToken","token","dPoP","createDPoP","getCreateDPoPOptions","accessToken","undefined","response","post","bearerToken","customHeaders","dpop","nextDPoPNonce","jwtPayloadProps","nonce","retryWithNonce","shouldRetryResourceRequestWithDPoPNonce","ok","dpopNonce","successDPoPNonce","origResponse","headers","isDeferredCredentialResponse","deferredCredentialAwait","successBody","acquireDeferredCredential","access_token","params","transactionId","transaction_id","acceptance_token","deferredCredentialIntervalInMS","formatSelection","getUniformFormat","typesSelection","length","types","Array","isArray","isV11OrHigher","proof","buildProof","OpenId4VCIVersion","VER_1_0_12","credential_definition","vct","doctype","VER_1_0_11","import_oid4vci_common","import_oid4vci_common","CredentialRequestClientBuilderV1_0_11","credentialEndpoint","deferredCredentialEndpoint","deferredCredentialAwait","deferredCredentialIntervalInMS","credentialTypes","format","token","version","subjectIssuance","issuerState","fromCredentialIssuer","credentialIssuer","metadata","issuer","builder","withVersion","OpenId4VCIVersion","VER_1_0_11","withCredentialEndpoint","credential_endpoint","endsWith","deferred_credential_endpoint","withDeferredCredentialEndpoint","withCredentialType","fromURI","uri","offer","CredentialOfferClientV1_0_11","fromCredentialOfferRequest","request","opts","determineSpecVersionFromOffer","original_credential_offer","getIssuerFromCredentialOfferPayload","credential_offer","VER_1_0_08","credential_type","getTypesFromOfferV1_0_11","fromCredentialOffer","credentialOffer","withIssuerState","withCredentialEndpointFromMetadata","withDeferredCredentialEndpointFromMetadata","withDeferredCredentialAwait","Array","isArray","withFormat","withSubjectIssuance","withToken","accessToken","withTokenFromResponse","response","access_token","build","CredentialRequestClientV1_0_11","import_oid4vci_common","CredentialRequestClientBuilderV1_0_13","credentialEndpoint","deferredCredentialEndpoint","deferredCredentialAwait","deferredCredentialIntervalInMS","credentialIdentifier","credentialTypes","format","token","version","subjectIssuance","issuerState","fromCredentialIssuer","credentialIssuer","metadata","issuer","builder","withVersion","OpenId4VCIVersion","VER_1_0_13","withCredentialEndpoint","credential_endpoint","endsWith","deferred_credential_endpoint","withDeferredCredentialEndpoint","withCredentialIdentifier","withCredentialType","fromURI","uri","offer","CredentialOfferClient","fromCredentialOfferRequest","request","opts","determineSpecVersionFromOffer","original_credential_offer","Error","getIssuerFromCredentialOfferPayload","credential_offer","ids","credential_configuration_ids","length","fromCredentialOffer","credentialOffer","withCredentialEndpointFromMetadata","withIssuerState","withDeferredCredentialEndpointFromMetadata","withDeferredCredentialAwait","Array","isArray","withFormat","withSubjectIssuance","withToken","accessToken","withTokenFromResponse","response","access_token","build","VER_1_0_11","CredentialRequestClient","isV1_0_13","builder","withCredentialIdentifier","undefined","CredentialRequestClientBuilder","_builder","fromCredentialIssuer","credentialIssuer","metadata","version","credentialIdentifier","credentialTypes","specVersion","OpenId4VCIVersion","VER_1_0_13","CredentialRequestClientBuilderV1_0_13","length","Error","CredentialRequestClientBuilderV1_0_11","fromURI","uri","offer","CredentialOfferClient","fromCredentialOfferRequest","request","opts","determineSpecVersionFromOffer","original_credential_offer","fromCredentialOffer","credentialOffer","credential_offer","getVersion","withCredentialEndpointFromMetadata","withCredentialEndpoint","credentialEndpoint","withDeferredCredentialEndpointFromMetadata","withDeferredCredentialEndpoint","deferredCredentialEndpoint","withDeferredCredentialAwait","deferredCredentialAwait","deferredCredentialIntervalInMS","withIssuerState","issuerState","withCredentialType","withFormat","format","withSubjectIssuance","subjectIssuance","withToken","accessToken","withTokenFromResponse","response","withVersion","build","import_oid4vci_common","import_ssi_types","logger","Loggers","DEFAULT","get","OpenID4VCIClient","_state","credentialOffer","clientId","kid","alg","credentialIssuer","pkce","authorizationRequest","accessToken","jwk","endpointMetadata","accessTokenResponse","authorizationRequestOpts","authorizationCodeResponse","authorizationURL","issuer","getIssuerFromCredentialOfferPayload","credential_offer","undefined","Error","getClientIdFromCredentialOfferPayload","split","disabled","codeChallengeMethod","CodeChallengeMethod","S256","credentialIssuerMetadata","authorization_server","syncAuthorizationRequestOpts","debug","JSON","stringify","fromCredentialIssuer","retrieveServerMetadata","createAuthorizationRequestURL","client","createAuthorizationRequestUrl","fromState","state","clientState","parse","fromURI","uri","resolveOfferUri","credentialOfferClient","CredentialOfferClient","resolve","supportedFlows","includes","AuthzFlowType","AUTHORIZATION_CODE_FLOW","opts","calculatePKCEOpts","authorization_endpoint","version","OpenId4VCIVersion","VER_1_0_11","createAuthorizationRequestUrlV1_0_11","credentialsSupported","Object","values","getCredentialsSupported","credentialConfigurationSupported","assertIssuerData","MetadataClient","retrieveAllMetadataFromCredentialOffer","retrieveAllMetadata","generateMissingPKCEOpts","acquireAuthorizationChallengeCode","response","acquireAuthorizationChallengeAuthCode","metadata","getIssuer","errorBody","error","Promise","reject","successBody","authorization_challenge_endpoint","acquireAccessToken","pin","redirectUri","code","getAuthorizationCode","authorizationResponse","codeVerifier","asOpts","clientOpts","requestObjectOpts","clientAssertionType","signCallbacks","signCallback","isEBSI","accessTokenClient","VER_1_0_12","AccessTokenClientV1_0_11","AccessTokenClient","console","log","createDPoPOpts","additionalRequestParams","additionalParams","token_endpoint","origResponse","status","dpopResponseParams","params","access_token","acquireCredentials","credentialTypes","context","proofCallbacks","format","jti","deferredCredentialAwait","deferredCredentialIntervalInMS","filter","v","length","KID_JWK_X5C_ERROR","requestBuilder","VER_1_0_13","CredentialRequestClientBuilderV1_0_11","fromCredentialOffer","CredentialRequestClientBuilderV1_0_13","issuerState","issuerSupportedFlowTypes","c_nonce","withIssuerState","withTokenFromResponse","withDeferredCredentialAwait","subjectIssuance","types","Array","isArray","credentials_supported","typeSupported","forEach","supportedCredential","subTypes","getTypesFromCredentialSupported","every","t","i","id","credential_subject_issuance","some","type","withSubjectIssuance","credentialRequestClient","build","proofBuilder","ProofOfPossessionBuilder","fromAccessTokenResponse","callbacks","withIssuer","withAlg","withJWK","withKid","withClientId","withJti","acquireCredentialsUsingProof","proofInput","credential_endpoint","exportState","restrictToInitiationTypes","getSupportedCredentials","issuerMetadata","getCredentialOfferTypes","sendNotification","credentialRequestOpts","request","orig","original_credential_offer","credential_type","result","credentials","map","c","getTypesFromObject","isFlowTypeSupported","flowType","hasAuthorizationURL","VER_UNKNOWN","versions","determineVersionsFromIssuerMetadata","assertServerMetadata","value","hasAccessTokenResponse","assertAccessToken","getAccessTokenEndpoint","determineTokenURL","issuerOpts","getCredentialEndpoint","getAuthorizationChallengeEndpoint","hasAuthorizationChallengeEndpoint","hasDeferredCredentialEndpoint","getDeferredCredentialEndpoint","find","cred","trust_framework","name","DefaultURISchemes","CREDENTIAL_OFFER","toAuthorizationResponsePayload","authorization_code","import_oid4vci_common","import_ssi_types","logger","Loggers","DEFAULT","get","OpenID4VCIClientV1_0_13","_state","credentialOffer","clientId","kid","alg","credentialIssuer","pkce","authorizationRequest","accessToken","jwk","endpointMetadata","accessTokenResponse","authorizationRequestOpts","authorizationCodeResponse","authorizationURL","issuer","getIssuerFromCredentialOfferPayload","credential_offer","undefined","Error","getClientIdFromCredentialOfferPayload","split","disabled","codeChallengeMethod","CodeChallengeMethod","S256","syncAuthorizationRequestOpts","debug","JSON","stringify","fromCredentialIssuer","retrieveServerMetadata","createAuthorizationRequestURL","client","createAuthorizationRequestUrl","fromState","state","clientState","parse","fromURI","uri","resolveOfferUri","credentialOfferClient","CredentialOfferClient","resolve","supportedFlows","includes","AuthzFlowType","AUTHORIZATION_CODE_FLOW","opts","calculatePKCEOpts","credentialIssuerMetadata","authorization_endpoint","credentialConfigurationSupported","getCredentialsSupported","version","assertIssuerData","MetadataClientV1_0_13","retrieveAllMetadataFromCredentialOffer","retrieveAllMetadata","generateMissingPKCEOpts","acquireAuthorizationChallengeCode","response","acquireAuthorizationChallengeAuthCode","metadata","getIssuer","errorBody","error","Promise","reject","successBody","authorization_challenge_endpoint","acquireAccessToken","pin","redirectUri","code","getAuthorizationCode","authorizationResponse","codeVerifier","asOpts","clientOpts","requestObjectOpts","clientAssertionType","signCallbacks","signCallback","isEBSI","accessTokenClient","AccessTokenClient","console","log","createDPoPOpts","additionalRequestParams","additionalParams","token_endpoint","origResponse","status","dpopResponseParams","params","access_token","acquireCredentialsWithoutProof","args","acquireCredentialsImpl","acquireCredentials","credentialIdentifier","credentialTypes","context","proofCallbacks","format","jti","deferredCredentialAwait","deferredCredentialIntervalInMS","filter","v","length","KID_JWK_X5C_ERROR","requestBuilder","CredentialRequestClientBuilderV1_0_13","fromCredentialOffer","issuerState","issuerSupportedFlowTypes","c_nonce","withIssuerState","withTokenFromResponse","withDeferredCredentialAwait","subjectIssuance","types","Array","isArray","credential_configurations_supported","credentialsSupported","credentials_supported","typeSupported","forEach","supportedCredential","subTypes","getTypesFromCredentialSupported","every","t","i","id","credential_subject_issuance","Object","values","withSubjectIssuance","credentialRequestClient","build","proofBuilder","ProofOfPossessionBuilder","fromAccessTokenResponse","callbacks","withIssuer","withAlg","withJWK","withKid","withClientId","withJti","request","createCredentialRequest","proofInput","createCredentialRequestWithoutProof","acquireCredentialsUsingRequest","credential_endpoint","exportState","getSupportedCredentials","issuerMetadata","sendNotification","credentialRequestOpts","isFlowTypeSupported","flowType","hasAuthorizationURL","OpenId4VCIVersion","VER_1_0_13","assertServerMetadata","value","hasAccessTokenResponse","assertAccessToken","getAccessTokenEndpoint","determineTokenURL","issuerOpts","getCredentialEndpoint","hasDeferredCredentialEndpoint","getDeferredCredentialEndpoint","credential_configuration_ids","credentialConfigurations","isEBSITrustFramework","map","config","trust_framework","some","name","authorization_server","DefaultURISchemes","CREDENTIAL_OFFER","toAuthorizationResponsePayload","authorization_code","import_oid4vci_common","import_ssi_types","logger","Loggers","DEFAULT","get","OpenID4VCIClientV1_0_11","_state","credentialOffer","clientId","kid","alg","credentialIssuer","pkce","authorizationRequest","jwk","endpointMetadata","accessTokenResponse","authorizationRequestOpts","authorizationCodeResponse","authorizationURL","issuer","getIssuerFromCredentialOfferPayload","credential_offer","undefined","Error","getClientIdFromCredentialOfferPayload","split","disabled","codeChallengeMethod","CodeChallengeMethod","S256","syncAuthorizationRequestOpts","debug","JSON","stringify","fromCredentialIssuer","retrieveServerMetadata","createAuthorizationRequestURL","client","createAuthorizationRequestUrl","fromState","state","clientState","parse","fromURI","uri","resolveOfferUri","credentialOfferClient","CredentialOfferClientV1_0_11","resolve","supportedFlows","includes","AuthzFlowType","AUTHORIZATION_CODE_FLOW","opts","calculatePKCEOpts","credentialIssuerMetadata","authorization_endpoint","createAuthorizationRequestUrlV1_0_11","credentialsSupported","Object","values","getCredentialsSupported","assertIssuerData","MetadataClientV1_0_11","retrieveAllMetadataFromCredentialOffer","retrieveAllMetadata","generateMissingPKCEOpts","acquireAuthorizationChallengeCode","response","acquireAuthorizationChallengeAuthCode","metadata","getIssuer","errorBody","error","Promise","reject","successBody","authorization_challenge_endpoint","acquireAccessToken","pin","redirectUri","code","getAuthorizationCode","authorizationResponse","codeVerifier","asOpts","clientOpts","accessTokenClient","AccessTokenClientV1_0_11","console","log","requestObjectOpts","clientAssertionType","signCallbacks","signCallback","isEBSI","createDPoPOpts","additionalRequestParams","additionalParams","token_endpoint","origResponse","status","dpopResponseParams","params","accessToken","access_token","acquireCredentials","credentialTypes","context","proofCallbacks","format","jti","deferredCredentialAwait","deferredCredentialIntervalInMS","filter","v","length","KID_JWK_X5C_ERROR","requestBuilder","CredentialRequestClientBuilderV1_0_11","fromCredentialOffer","version","withTokenFromResponse","withDeferredCredentialAwait","types","Array","isArray","credentials_supported","typeSupported","forEach","supportedCredential","subTypes","getTypesFromCredentialSupported","every","t","i","id","some","type","credentialRequestClient","build","proofBuilder","ProofOfPossessionBuilder","fromAccessTokenResponse","callbacks","withIssuer","withAlg","withJWK","withKid","withClientId","withJti","acquireCredentialsUsingProof","proofInput","credential_endpoint","exportState","getCredentialsSupportedV11","restrictToInitiationTypes","getSupportedCredentials","issuerMetadata","getCredentialOfferTypes","OpenId4VCIVersion","VER_1_0_11","orig","original_credential_offer","credential_type","result","VER_1_0_13","credentials","map","c","getTypesFromObject","issuerSupportedFlowTypes","isFlowTypeSupported","flowType","hasAuthorizationURL","assertServerMetadata","value","hasAccessTokenResponse","assertAccessToken","getAccessTokenEndpoint","determineTokenURL","issuerOpts","getCredentialEndpoint","hasDeferredCredentialEndpoint","getDeferredCredentialEndpoint","find","cred","trust_framework","name","authorization_server","DefaultURISchemes","CREDENTIAL_OFFER","toAuthorizationResponsePayload","authorization_code","LOG","VCI_LOGGERS","get"]}