'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var tslib = require('tslib');
var coreRestPipeline = require('@azure/core-rest-pipeline');
var logger$1 = require('@azure/logger');
var coreClient = require('@azure/core-client');
var coreHttpCompat = require('@azure/core-http-compat');
var coreLro = require('@azure/core-lro');
var coreUtil = require('@azure/core-util');
var coreTracing = require('@azure/core-tracing');

function _interopNamespaceDefault(e) {
    var n = Object.create(null);
    if (e) {
        Object.keys(e).forEach(function (k) {
            if (k !== 'default') {
                var d = Object.getOwnPropertyDescriptor(e, k);
                Object.defineProperty(n, k, d.get ? d : {
                    enumerable: true,
                    get: function () { return e[k]; }
                });
            }
        });
    }
    n.default = e;
    return Object.freeze(n);
}

var coreRestPipeline__namespace = /*#__PURE__*/_interopNamespaceDefault(coreRestPipeline);
var coreClient__namespace = /*#__PURE__*/_interopNamespaceDefault(coreClient);
var coreHttpCompat__namespace = /*#__PURE__*/_interopNamespaceDefault(coreHttpCompat);

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
 * The \@azure/logger configuration for this package.
 */
const logger = logger$1.createClientLogger("keyvault-secrets");

/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT License.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is regenerated.
 */
/** Known values of {@link ApiVersion75} that the service accepts. */
var KnownApiVersion75;
(function (KnownApiVersion75) {
    /** Api Version '7.5' */
    KnownApiVersion75["Seven5"] = "7.5";
})(KnownApiVersion75 || (KnownApiVersion75 = {}));
/** Known values of {@link DeletionRecoveryLevel} that the service accepts. */
exports.KnownDeletionRecoveryLevel = void 0;
(function (KnownDeletionRecoveryLevel) {
    /** Denotes a vault state in which deletion is an irreversible operation, without the possibility for recovery. This level corresponds to no protection being available against a Delete operation; the data is irretrievably lost upon accepting a Delete operation at the entity level or higher (vault, resource group, subscription etc.) */
    KnownDeletionRecoveryLevel["Purgeable"] = "Purgeable";
    /** Denotes a vault state in which deletion is recoverable, and which also permits immediate and permanent deletion (i.e. purge). This level guarantees the recoverability of the deleted entity during the retention interval (90 days), unless a Purge operation is requested, or the subscription is cancelled. System wil permanently delete it after 90 days, if not recovered */
    KnownDeletionRecoveryLevel["RecoverablePurgeable"] = "Recoverable+Purgeable";
    /** Denotes a vault state in which deletion is recoverable without the possibility for immediate and permanent deletion (i.e. purge). This level guarantees the recoverability of the deleted entity during the retention interval(90 days) and while the subscription is still available. System wil permanently delete it after 90 days, if not recovered */
    KnownDeletionRecoveryLevel["Recoverable"] = "Recoverable";
    /** Denotes a vault and subscription state in which deletion is recoverable within retention interval (90 days), immediate and permanent deletion (i.e. purge) is not permitted, and in which the subscription itself  cannot be permanently canceled. System wil permanently delete it after 90 days, if not recovered */
    KnownDeletionRecoveryLevel["RecoverableProtectedSubscription"] = "Recoverable+ProtectedSubscription";
    /** Denotes a vault state in which deletion is recoverable, and which also permits immediate and permanent deletion (i.e. purge when 7<= SoftDeleteRetentionInDays < 90). This level guarantees the recoverability of the deleted entity during the retention interval, unless a Purge operation is requested, or the subscription is cancelled. */
    KnownDeletionRecoveryLevel["CustomizedRecoverablePurgeable"] = "CustomizedRecoverable+Purgeable";
    /** Denotes a vault state in which deletion is recoverable without the possibility for immediate and permanent deletion (i.e. purge when 7<= SoftDeleteRetentionInDays < 90).This level guarantees the recoverability of the deleted entity during the retention interval and while the subscription is still available. */
    KnownDeletionRecoveryLevel["CustomizedRecoverable"] = "CustomizedRecoverable";
    /** Denotes a vault and subscription state in which deletion is recoverable, immediate and permanent deletion (i.e. purge) is not permitted, and in which the subscription itself cannot be permanently canceled when 7<= SoftDeleteRetentionInDays < 90. This level guarantees the recoverability of the deleted entity during the retention interval, and also reflects the fact that the subscription itself cannot be cancelled. */
    KnownDeletionRecoveryLevel["CustomizedRecoverableProtectedSubscription"] = "CustomizedRecoverable+ProtectedSubscription";
})(exports.KnownDeletionRecoveryLevel || (exports.KnownDeletionRecoveryLevel = {}));

/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT License.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is regenerated.
 */
const SecretSetParameters = {
    type: {
        name: "Composite",
        className: "SecretSetParameters",
        modelProperties: {
            value: {
                serializedName: "value",
                required: true,
                type: {
                    name: "String"
                }
            },
            tags: {
                serializedName: "tags",
                type: {
                    name: "Dictionary",
                    value: { type: { name: "String" } }
                }
            },
            contentType: {
                serializedName: "contentType",
                type: {
                    name: "String"
                }
            },
            secretAttributes: {
                serializedName: "attributes",
                type: {
                    name: "Composite",
                    className: "SecretAttributes"
                }
            }
        }
    }
};
const Attributes = {
    type: {
        name: "Composite",
        className: "Attributes",
        modelProperties: {
            enabled: {
                serializedName: "enabled",
                type: {
                    name: "Boolean"
                }
            },
            notBefore: {
                serializedName: "nbf",
                type: {
                    name: "UnixTime"
                }
            },
            expires: {
                serializedName: "exp",
                type: {
                    name: "UnixTime"
                }
            },
            created: {
                serializedName: "created",
                readOnly: true,
                type: {
                    name: "UnixTime"
                }
            },
            updated: {
                serializedName: "updated",
                readOnly: true,
                type: {
                    name: "UnixTime"
                }
            }
        }
    }
};
const SecretBundle = {
    type: {
        name: "Composite",
        className: "SecretBundle",
        modelProperties: {
            value: {
                serializedName: "value",
                type: {
                    name: "String"
                }
            },
            id: {
                serializedName: "id",
                type: {
                    name: "String"
                }
            },
            contentType: {
                serializedName: "contentType",
                type: {
                    name: "String"
                }
            },
            attributes: {
                serializedName: "attributes",
                type: {
                    name: "Composite",
                    className: "SecretAttributes"
                }
            },
            tags: {
                serializedName: "tags",
                type: {
                    name: "Dictionary",
                    value: { type: { name: "String" } }
                }
            },
            kid: {
                serializedName: "kid",
                readOnly: true,
                type: {
                    name: "String"
                }
            },
            managed: {
                serializedName: "managed",
                readOnly: true,
                type: {
                    name: "Boolean"
                }
            }
        }
    }
};
const KeyVaultError = {
    type: {
        name: "Composite",
        className: "KeyVaultError",
        modelProperties: {
            error: {
                serializedName: "error",
                type: {
                    name: "Composite",
                    className: "ErrorModel"
                }
            }
        }
    }
};
const ErrorModel = {
    type: {
        name: "Composite",
        className: "ErrorModel",
        modelProperties: {
            code: {
                serializedName: "code",
                readOnly: true,
                type: {
                    name: "String"
                }
            },
            message: {
                serializedName: "message",
                readOnly: true,
                type: {
                    name: "String"
                }
            },
            innerError: {
                serializedName: "innererror",
                type: {
                    name: "Composite",
                    className: "ErrorModel"
                }
            }
        }
    }
};
const SecretUpdateParameters = {
    type: {
        name: "Composite",
        className: "SecretUpdateParameters",
        modelProperties: {
            contentType: {
                serializedName: "contentType",
                type: {
                    name: "String"
                }
            },
            secretAttributes: {
                serializedName: "attributes",
                type: {
                    name: "Composite",
                    className: "SecretAttributes"
                }
            },
            tags: {
                serializedName: "tags",
                type: {
                    name: "Dictionary",
                    value: { type: { name: "String" } }
                }
            }
        }
    }
};
const SecretListResult = {
    type: {
        name: "Composite",
        className: "SecretListResult",
        modelProperties: {
            value: {
                serializedName: "value",
                readOnly: true,
                type: {
                    name: "Sequence",
                    element: {
                        type: {
                            name: "Composite",
                            className: "SecretItem"
                        }
                    }
                }
            },
            nextLink: {
                serializedName: "nextLink",
                readOnly: true,
                type: {
                    name: "String"
                }
            }
        }
    }
};
const SecretItem = {
    type: {
        name: "Composite",
        className: "SecretItem",
        modelProperties: {
            id: {
                serializedName: "id",
                type: {
                    name: "String"
                }
            },
            attributes: {
                serializedName: "attributes",
                type: {
                    name: "Composite",
                    className: "SecretAttributes"
                }
            },
            tags: {
                serializedName: "tags",
                type: {
                    name: "Dictionary",
                    value: { type: { name: "String" } }
                }
            },
            contentType: {
                serializedName: "contentType",
                type: {
                    name: "String"
                }
            },
            managed: {
                serializedName: "managed",
                readOnly: true,
                type: {
                    name: "Boolean"
                }
            }
        }
    }
};
const DeletedSecretListResult = {
    type: {
        name: "Composite",
        className: "DeletedSecretListResult",
        modelProperties: {
            value: {
                serializedName: "value",
                readOnly: true,
                type: {
                    name: "Sequence",
                    element: {
                        type: {
                            name: "Composite",
                            className: "DeletedSecretItem"
                        }
                    }
                }
            },
            nextLink: {
                serializedName: "nextLink",
                readOnly: true,
                type: {
                    name: "String"
                }
            }
        }
    }
};
const BackupSecretResult = {
    type: {
        name: "Composite",
        className: "BackupSecretResult",
        modelProperties: {
            value: {
                serializedName: "value",
                readOnly: true,
                type: {
                    name: "Base64Url"
                }
            }
        }
    }
};
const SecretRestoreParameters = {
    type: {
        name: "Composite",
        className: "SecretRestoreParameters",
        modelProperties: {
            secretBundleBackup: {
                serializedName: "value",
                required: true,
                type: {
                    name: "Base64Url"
                }
            }
        }
    }
};
const SecretProperties = {
    type: {
        name: "Composite",
        className: "SecretProperties",
        modelProperties: {
            contentType: {
                serializedName: "contentType",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const SecretAttributes = {
    type: {
        name: "Composite",
        className: "SecretAttributes",
        modelProperties: Object.assign(Object.assign({}, Attributes.type.modelProperties), { recoverableDays: {
                serializedName: "recoverableDays",
                readOnly: true,
                type: {
                    name: "Number"
                }
            }, recoveryLevel: {
                serializedName: "recoveryLevel",
                readOnly: true,
                type: {
                    name: "String"
                }
            } })
    }
};
const DeletedSecretBundle = {
    type: {
        name: "Composite",
        className: "DeletedSecretBundle",
        modelProperties: Object.assign(Object.assign({}, SecretBundle.type.modelProperties), { recoveryId: {
                serializedName: "recoveryId",
                type: {
                    name: "String"
                }
            }, scheduledPurgeDate: {
                serializedName: "scheduledPurgeDate",
                readOnly: true,
                type: {
                    name: "UnixTime"
                }
            }, deletedDate: {
                serializedName: "deletedDate",
                readOnly: true,
                type: {
                    name: "UnixTime"
                }
            } })
    }
};
const DeletedSecretItem = {
    type: {
        name: "Composite",
        className: "DeletedSecretItem",
        modelProperties: Object.assign(Object.assign({}, SecretItem.type.modelProperties), { recoveryId: {
                serializedName: "recoveryId",
                type: {
                    name: "String"
                }
            }, scheduledPurgeDate: {
                serializedName: "scheduledPurgeDate",
                readOnly: true,
                type: {
                    name: "UnixTime"
                }
            }, deletedDate: {
                serializedName: "deletedDate",
                readOnly: true,
                type: {
                    name: "UnixTime"
                }
            } })
    }
};

var Mappers = /*#__PURE__*/Object.freeze({
    __proto__: null,
    Attributes: Attributes,
    BackupSecretResult: BackupSecretResult,
    DeletedSecretBundle: DeletedSecretBundle,
    DeletedSecretItem: DeletedSecretItem,
    DeletedSecretListResult: DeletedSecretListResult,
    ErrorModel: ErrorModel,
    KeyVaultError: KeyVaultError,
    SecretAttributes: SecretAttributes,
    SecretBundle: SecretBundle,
    SecretItem: SecretItem,
    SecretListResult: SecretListResult,
    SecretProperties: SecretProperties,
    SecretRestoreParameters: SecretRestoreParameters,
    SecretSetParameters: SecretSetParameters,
    SecretUpdateParameters: SecretUpdateParameters
});

/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT License.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is regenerated.
 */
const contentType = {
    parameterPath: ["options", "contentType"],
    mapper: {
        defaultValue: "application/json",
        isConstant: true,
        serializedName: "Content-Type",
        type: {
            name: "String"
        }
    }
};
const accept = {
    parameterPath: "accept",
    mapper: {
        defaultValue: "application/json",
        isConstant: true,
        serializedName: "Accept",
        type: {
            name: "String"
        }
    }
};
const vaultBaseUrl = {
    parameterPath: "vaultBaseUrl",
    mapper: {
        serializedName: "vaultBaseUrl",
        required: true,
        type: {
            name: "String"
        }
    },
    skipEncoding: true
};
const secretName = {
    parameterPath: "secretName",
    mapper: {
        constraints: {
            Pattern: new RegExp("^[0-9a-zA-Z-]+$")
        },
        serializedName: "secret-name",
        required: true,
        type: {
            name: "String"
        }
    }
};
const apiVersion = {
    parameterPath: "apiVersion",
    mapper: {
        serializedName: "api-version",
        required: true,
        type: {
            name: "String"
        }
    }
};
const secretName1 = {
    parameterPath: "secretName",
    mapper: {
        serializedName: "secret-name",
        required: true,
        type: {
            name: "String"
        }
    }
};
const secretVersion = {
    parameterPath: "secretVersion",
    mapper: {
        serializedName: "secret-version",
        required: true,
        type: {
            name: "String"
        }
    }
};
const maxresults = {
    parameterPath: ["options", "maxresults"],
    mapper: {
        constraints: {
            InclusiveMaximum: 25,
            InclusiveMinimum: 1
        },
        serializedName: "maxresults",
        type: {
            name: "Number"
        }
    }
};
const nextLink = {
    parameterPath: "nextLink",
    mapper: {
        serializedName: "nextLink",
        required: true,
        type: {
            name: "String"
        }
    },
    skipEncoding: true
};

/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT License.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is regenerated.
 */
/** @internal */
class KeyVaultClient extends coreHttpCompat__namespace.ExtendedServiceClient {
    /**
     * Initializes a new instance of the KeyVaultClient class.
     * @param apiVersion Api Version
     * @param options The parameter options
     */
    constructor(apiVersion, options) {
        var _a, _b;
        if (apiVersion === undefined) {
            throw new Error("'apiVersion' cannot be null");
        }
        // Initializing default values for options
        if (!options) {
            options = {};
        }
        const defaults = {
            requestContentType: "application/json; charset=utf-8"
        };
        const packageDetails = `azsdk-js-keyvault-secrets/4.8.0`;
        const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix
            ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
            : `${packageDetails}`;
        const optionsWithDefaults = Object.assign(Object.assign(Object.assign({}, defaults), options), { userAgentOptions: {
                userAgentPrefix
            }, baseUri: (_b = (_a = options.endpoint) !== null && _a !== void 0 ? _a : options.baseUri) !== null && _b !== void 0 ? _b : "{vaultBaseUrl}" });
        super(optionsWithDefaults);
        if ((options === null || options === void 0 ? void 0 : options.pipeline) && options.pipeline.getOrderedPolicies().length > 0) {
            const pipelinePolicies = options.pipeline.getOrderedPolicies();
            const bearerTokenAuthenticationPolicyFound = pipelinePolicies.some((pipelinePolicy) => pipelinePolicy.name ===
                coreRestPipeline__namespace.bearerTokenAuthenticationPolicyName);
            if (!bearerTokenAuthenticationPolicyFound) {
                this.pipeline.removePolicy({
                    name: coreRestPipeline__namespace.bearerTokenAuthenticationPolicyName
                });
                this.pipeline.addPolicy(coreRestPipeline__namespace.bearerTokenAuthenticationPolicy({
                    scopes: `${optionsWithDefaults.baseUri}/.default`,
                    challengeCallbacks: {
                        authorizeRequestOnChallenge: coreClient__namespace.authorizeRequestOnClaimChallenge
                    }
                }));
            }
        }
        // Parameter assignments
        this.apiVersion = apiVersion;
    }
    /**
     *  The SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure
     * Key Vault creates a new version of that secret. This operation requires the secrets/set permission.
     * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
     * @param secretName The name of the secret. The value you provide may be copied globally for the
     *                   purpose of running the service. The value provided should not include personally identifiable or
     *                   sensitive information.
     * @param value The value of the secret.
     * @param options The options parameters.
     */
    setSecret(vaultBaseUrl, secretName, value, options) {
        return this.sendOperationRequest({ vaultBaseUrl, secretName, value, options }, setSecretOperationSpec);
    }
    /**
     * The DELETE operation applies to any secret stored in Azure Key Vault. DELETE cannot be applied to an
     * individual version of a secret. This operation requires the secrets/delete permission.
     * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
     * @param secretName The name of the secret.
     * @param options The options parameters.
     */
    deleteSecret(vaultBaseUrl, secretName, options) {
        return this.sendOperationRequest({ vaultBaseUrl, secretName, options }, deleteSecretOperationSpec);
    }
    /**
     * The UPDATE operation changes specified attributes of an existing stored secret. Attributes that are
     * not specified in the request are left unchanged. The value of a secret itself cannot be changed.
     * This operation requires the secrets/set permission.
     * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
     * @param secretName The name of the secret.
     * @param secretVersion The version of the secret.
     * @param options The options parameters.
     */
    updateSecret(vaultBaseUrl, secretName, secretVersion, options) {
        return this.sendOperationRequest({ vaultBaseUrl, secretName, secretVersion, options }, updateSecretOperationSpec);
    }
    /**
     * The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the
     * secrets/get permission.
     * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
     * @param secretName The name of the secret.
     * @param secretVersion The version of the secret. This URI fragment is optional. If not specified, the
     *                      latest version of the secret is returned.
     * @param options The options parameters.
     */
    getSecret(vaultBaseUrl, secretName, secretVersion, options) {
        return this.sendOperationRequest({ vaultBaseUrl, secretName, secretVersion, options }, getSecretOperationSpec);
    }
    /**
     * The Get Secrets operation is applicable to the entire vault. However, only the base secret
     * identifier and its attributes are provided in the response. Individual secret versions are not
     * listed in the response. This operation requires the secrets/list permission.
     * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
     * @param options The options parameters.
     */
    getSecrets(vaultBaseUrl, options) {
        return this.sendOperationRequest({ vaultBaseUrl, options }, getSecretsOperationSpec);
    }
    /**
     * The full secret identifier and attributes are provided in the response. No values are returned for
     * the secrets. This operations requires the secrets/list permission.
     * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
     * @param secretName The name of the secret.
     * @param options The options parameters.
     */
    getSecretVersions(vaultBaseUrl, secretName, options) {
        return this.sendOperationRequest({ vaultBaseUrl, secretName, options }, getSecretVersionsOperationSpec);
    }
    /**
     * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for
     * soft-delete. This operation requires the secrets/list permission.
     * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
     * @param options The options parameters.
     */
    getDeletedSecrets(vaultBaseUrl, options) {
        return this.sendOperationRequest({ vaultBaseUrl, options }, getDeletedSecretsOperationSpec);
    }
    /**
     * The Get Deleted Secret operation returns the specified deleted secret along with its attributes.
     * This operation requires the secrets/get permission.
     * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
     * @param secretName The name of the secret.
     * @param options The options parameters.
     */
    getDeletedSecret(vaultBaseUrl, secretName, options) {
        return this.sendOperationRequest({ vaultBaseUrl, secretName, options }, getDeletedSecretOperationSpec);
    }
    /**
     * The purge deleted secret operation removes the secret permanently, without the possibility of
     * recovery. This operation can only be enabled on a soft-delete enabled vault. This operation requires
     * the secrets/purge permission.
     * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
     * @param secretName The name of the secret.
     * @param options The options parameters.
     */
    purgeDeletedSecret(vaultBaseUrl, secretName, options) {
        return this.sendOperationRequest({ vaultBaseUrl, secretName, options }, purgeDeletedSecretOperationSpec);
    }
    /**
     * Recovers the deleted secret in the specified vault. This operation can only be performed on a
     * soft-delete enabled vault. This operation requires the secrets/recover permission.
     * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
     * @param secretName The name of the deleted secret.
     * @param options The options parameters.
     */
    recoverDeletedSecret(vaultBaseUrl, secretName, options) {
        return this.sendOperationRequest({ vaultBaseUrl, secretName, options }, recoverDeletedSecretOperationSpec);
    }
    /**
     * Requests that a backup of the specified secret be downloaded to the client. All versions of the
     * secret will be downloaded. This operation requires the secrets/backup permission.
     * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
     * @param secretName The name of the secret.
     * @param options The options parameters.
     */
    backupSecret(vaultBaseUrl, secretName, options) {
        return this.sendOperationRequest({ vaultBaseUrl, secretName, options }, backupSecretOperationSpec);
    }
    /**
     * Restores a backed up secret, and all its versions, to a vault. This operation requires the
     * secrets/restore permission.
     * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
     * @param secretBundleBackup The backup blob associated with a secret bundle.
     * @param options The options parameters.
     */
    restoreSecret(vaultBaseUrl, secretBundleBackup, options) {
        return this.sendOperationRequest({ vaultBaseUrl, secretBundleBackup, options }, restoreSecretOperationSpec);
    }
    /**
     * GetSecretsNext
     * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
     * @param nextLink The nextLink from the previous successful call to the GetSecrets method.
     * @param options The options parameters.
     */
    getSecretsNext(vaultBaseUrl, nextLink, options) {
        return this.sendOperationRequest({ vaultBaseUrl, nextLink, options }, getSecretsNextOperationSpec);
    }
    /**
     * GetSecretVersionsNext
     * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
     * @param secretName The name of the secret.
     * @param nextLink The nextLink from the previous successful call to the GetSecretVersions method.
     * @param options The options parameters.
     */
    getSecretVersionsNext(vaultBaseUrl, secretName, nextLink, options) {
        return this.sendOperationRequest({ vaultBaseUrl, secretName, nextLink, options }, getSecretVersionsNextOperationSpec);
    }
    /**
     * GetDeletedSecretsNext
     * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
     * @param nextLink The nextLink from the previous successful call to the GetDeletedSecrets method.
     * @param options The options parameters.
     */
    getDeletedSecretsNext(vaultBaseUrl, nextLink, options) {
        return this.sendOperationRequest({ vaultBaseUrl, nextLink, options }, getDeletedSecretsNextOperationSpec);
    }
}
// Operation Specifications
const serializer = coreClient__namespace.createSerializer(Mappers, /* isXml */ false);
const setSecretOperationSpec = {
    path: "/secrets/{secret-name}",
    httpMethod: "PUT",
    responses: {
        200: {
            bodyMapper: SecretBundle
        },
        default: {
            bodyMapper: KeyVaultError
        }
    },
    requestBody: {
        parameterPath: {
            value: ["value"],
            tags: ["options", "tags"],
            contentType: ["options", "contentType"],
            secretAttributes: ["options", "secretAttributes"]
        },
        mapper: Object.assign(Object.assign({}, SecretSetParameters), { required: true })
    },
    queryParameters: [apiVersion],
    urlParameters: [vaultBaseUrl, secretName],
    headerParameters: [contentType, accept],
    mediaType: "json",
    serializer
};
const deleteSecretOperationSpec = {
    path: "/secrets/{secret-name}",
    httpMethod: "DELETE",
    responses: {
        200: {
            bodyMapper: DeletedSecretBundle
        },
        default: {
            bodyMapper: KeyVaultError
        }
    },
    queryParameters: [apiVersion],
    urlParameters: [vaultBaseUrl, secretName1],
    headerParameters: [accept],
    serializer
};
const updateSecretOperationSpec = {
    path: "/secrets/{secret-name}/{secret-version}",
    httpMethod: "PATCH",
    responses: {
        200: {
            bodyMapper: SecretBundle
        },
        default: {
            bodyMapper: KeyVaultError
        }
    },
    requestBody: {
        parameterPath: {
            contentType: ["options", "contentType"],
            secretAttributes: ["options", "secretAttributes"],
            tags: ["options", "tags"]
        },
        mapper: Object.assign(Object.assign({}, SecretUpdateParameters), { required: true })
    },
    queryParameters: [apiVersion],
    urlParameters: [
        vaultBaseUrl,
        secretName1,
        secretVersion
    ],
    headerParameters: [contentType, accept],
    mediaType: "json",
    serializer
};
const getSecretOperationSpec = {
    path: "/secrets/{secret-name}/{secret-version}",
    httpMethod: "GET",
    responses: {
        200: {
            bodyMapper: SecretBundle
        },
        default: {
            bodyMapper: KeyVaultError
        }
    },
    queryParameters: [apiVersion],
    urlParameters: [
        vaultBaseUrl,
        secretName1,
        secretVersion
    ],
    headerParameters: [accept],
    serializer
};
const getSecretsOperationSpec = {
    path: "/secrets",
    httpMethod: "GET",
    responses: {
        200: {
            bodyMapper: SecretListResult
        },
        default: {
            bodyMapper: KeyVaultError
        }
    },
    queryParameters: [apiVersion, maxresults],
    urlParameters: [vaultBaseUrl],
    headerParameters: [accept],
    serializer
};
const getSecretVersionsOperationSpec = {
    path: "/secrets/{secret-name}/versions",
    httpMethod: "GET",
    responses: {
        200: {
            bodyMapper: SecretListResult
        },
        default: {
            bodyMapper: KeyVaultError
        }
    },
    queryParameters: [apiVersion, maxresults],
    urlParameters: [vaultBaseUrl, secretName1],
    headerParameters: [accept],
    serializer
};
const getDeletedSecretsOperationSpec = {
    path: "/deletedsecrets",
    httpMethod: "GET",
    responses: {
        200: {
            bodyMapper: DeletedSecretListResult
        },
        default: {
            bodyMapper: KeyVaultError
        }
    },
    queryParameters: [apiVersion, maxresults],
    urlParameters: [vaultBaseUrl],
    headerParameters: [accept],
    serializer
};
const getDeletedSecretOperationSpec = {
    path: "/deletedsecrets/{secret-name}",
    httpMethod: "GET",
    responses: {
        200: {
            bodyMapper: DeletedSecretBundle
        },
        default: {
            bodyMapper: KeyVaultError
        }
    },
    queryParameters: [apiVersion],
    urlParameters: [vaultBaseUrl, secretName1],
    headerParameters: [accept],
    serializer
};
const purgeDeletedSecretOperationSpec = {
    path: "/deletedsecrets/{secret-name}",
    httpMethod: "DELETE",
    responses: {
        204: {},
        default: {
            bodyMapper: KeyVaultError
        }
    },
    queryParameters: [apiVersion],
    urlParameters: [vaultBaseUrl, secretName1],
    headerParameters: [accept],
    serializer
};
const recoverDeletedSecretOperationSpec = {
    path: "/deletedsecrets/{secret-name}/recover",
    httpMethod: "POST",
    responses: {
        200: {
            bodyMapper: SecretBundle
        },
        default: {
            bodyMapper: KeyVaultError
        }
    },
    queryParameters: [apiVersion],
    urlParameters: [vaultBaseUrl, secretName1],
    headerParameters: [accept],
    serializer
};
const backupSecretOperationSpec = {
    path: "/secrets/{secret-name}/backup",
    httpMethod: "POST",
    responses: {
        200: {
            bodyMapper: BackupSecretResult
        },
        default: {
            bodyMapper: KeyVaultError
        }
    },
    queryParameters: [apiVersion],
    urlParameters: [vaultBaseUrl, secretName1],
    headerParameters: [accept],
    serializer
};
const restoreSecretOperationSpec = {
    path: "/secrets/restore",
    httpMethod: "POST",
    responses: {
        200: {
            bodyMapper: SecretBundle
        },
        default: {
            bodyMapper: KeyVaultError
        }
    },
    requestBody: {
        parameterPath: { secretBundleBackup: ["secretBundleBackup"] },
        mapper: Object.assign(Object.assign({}, SecretRestoreParameters), { required: true })
    },
    queryParameters: [apiVersion],
    urlParameters: [vaultBaseUrl],
    headerParameters: [contentType, accept],
    mediaType: "json",
    serializer
};
const getSecretsNextOperationSpec = {
    path: "{nextLink}",
    httpMethod: "GET",
    responses: {
        200: {
            bodyMapper: SecretListResult
        },
        default: {
            bodyMapper: KeyVaultError
        }
    },
    queryParameters: [apiVersion, maxresults],
    urlParameters: [vaultBaseUrl, nextLink],
    headerParameters: [accept],
    serializer
};
const getSecretVersionsNextOperationSpec = {
    path: "{nextLink}",
    httpMethod: "GET",
    responses: {
        200: {
            bodyMapper: SecretListResult
        },
        default: {
            bodyMapper: KeyVaultError
        }
    },
    queryParameters: [apiVersion, maxresults],
    urlParameters: [
        vaultBaseUrl,
        secretName1,
        nextLink
    ],
    headerParameters: [accept],
    serializer
};
const getDeletedSecretsNextOperationSpec = {
    path: "{nextLink}",
    httpMethod: "GET",
    responses: {
        200: {
            bodyMapper: DeletedSecretListResult
        },
        default: {
            bodyMapper: KeyVaultError
        }
    },
    queryParameters: [apiVersion, maxresults],
    urlParameters: [vaultBaseUrl, nextLink],
    headerParameters: [accept],
    serializer
};

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
const validWWWAuthenticateProperties = [
    "authorization",
    "authorization_url",
    "resource",
    "scope",
    "tenantId",
];
/**
 * Parses an WWW-Authenticate response header.
 * This transforms a string value like:
 * `Bearer authorization="https://some.url/tenantId", resource="https://some.url"`
 * into an object like:
 * `{ authorization: "https://some.url/tenantId", resource: "https://some.url" }`
 * @param headerValue - String value in the WWW-Authenticate header
 */
function parseWWWAuthenticateHeader(headerValue) {
    const pairDelimiter = /,? +/;
    const parsed = headerValue.split(pairDelimiter).reduce((kvPairs, p) => {
        if (p.match(/\w="/)) {
            // 'sampleKey="sample_value"' -> [sampleKey, "sample_value"] -> { sampleKey: sample_value }
            const [key, value] = p.split("=");
            if (validWWWAuthenticateProperties.includes(key)) {
                // The values will be wrapped in quotes, which need to be stripped out.
                return Object.assign(Object.assign({}, kvPairs), { [key]: value.slice(1, -1) });
            }
        }
        return kvPairs;
    }, {});
    // Finally, we pull the tenantId from the authorization header to support multi-tenant authentication.
    if (parsed.authorization) {
        try {
            const tenantId = new URL(parsed.authorization).pathname.substring(1);
            if (tenantId) {
                parsed.tenantId = tenantId;
            }
        }
        catch (_) {
            throw new Error(`The challenge authorization URI '${parsed.authorization}' is invalid.`);
        }
    }
    return parsed;
}

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
function verifyChallengeResource(scope, request) {
    let scopeAsUrl;
    try {
        scopeAsUrl = new URL(scope);
    }
    catch (e) {
        throw new Error(`The challenge contains invalid scope '${scope}'`);
    }
    const requestUrl = new URL(request.url);
    if (!requestUrl.hostname.endsWith(`.${scopeAsUrl.hostname}`)) {
        throw new Error(`The challenge resource '${scopeAsUrl.hostname}' does not match the requested domain. Set disableChallengeResourceVerification to true in your client options to disable. See https://aka.ms/azsdk/blog/vault-uri for more information.`);
    }
}
/**
 * Creates challenge callback handlers to manage CAE lifecycle in Azure Key Vault.
 *
 * Key Vault supports other authentication schemes, but we ensure challenge authentication
 * is used by first sending a copy of the request, without authorization or content.
 *
 * when the challenge is received, it will be authenticated and used to send the original
 * request with authorization.
 *
 * Following the first request of a client, follow-up requests will get the cached token
 * if possible.
 *
 */
function createKeyVaultChallengeCallbacks(options = {}) {
    const { disableChallengeResourceVerification } = options;
    let challengeState = { status: "none" };
    function requestToOptions(request) {
        return {
            abortSignal: request.abortSignal,
            requestOptions: {
                timeout: request.timeout > 0 ? request.timeout : undefined,
            },
            tracingOptions: request.tracingOptions,
        };
    }
    async function authorizeRequest({ request, getAccessToken, }) {
        const requestOptions = requestToOptions(request);
        switch (challengeState.status) {
            case "none":
                challengeState = {
                    status: "started",
                    originalBody: request.body,
                };
                request.body = null;
                break;
            case "started":
                break; // Retry, we should not overwrite the original body
            case "complete": {
                const token = await getAccessToken(challengeState.scopes, requestOptions);
                if (token) {
                    request.headers.set("authorization", `Bearer ${token.token}`);
                }
                break;
            }
        }
        return Promise.resolve();
    }
    async function authorizeRequestOnChallenge({ request, response, getAccessToken, }) {
        if (request.body === null && challengeState.status === "started") {
            // Reset the original body before doing anything else.
            // Note: If successful status will be "complete", otherwise "none" will
            // restart the process.
            request.body = challengeState.originalBody;
        }
        const getTokenOptions = requestToOptions(request);
        const challenge = response.headers.get("WWW-Authenticate");
        if (!challenge) {
            throw new Error("Missing challenge.");
        }
        const parsedChallenge = parseWWWAuthenticateHeader(challenge) || {};
        const scope = parsedChallenge.resource
            ? parsedChallenge.resource + "/.default"
            : parsedChallenge.scope;
        if (!scope) {
            throw new Error("Missing scope.");
        }
        if (!disableChallengeResourceVerification) {
            verifyChallengeResource(scope, request);
        }
        const accessToken = await getAccessToken([scope], Object.assign(Object.assign({}, getTokenOptions), { tenantId: parsedChallenge.tenantId }));
        if (!accessToken) {
            return false;
        }
        request.headers.set("Authorization", `Bearer ${accessToken.token}`);
        challengeState = {
            status: "complete",
            scopes: [scope],
        };
        return true;
    }
    return {
        authorizeRequest,
        authorizeRequestOnChallenge,
    };
}

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
 * Parses a Key Vault identifier into its components.
 *
 * @param collection - The collection of the Key Vault identifier.
 * @param identifier - The Key Vault identifier to be parsed.
 */
function parseKeyVaultIdentifier(collection, identifier) {
    if (typeof collection !== "string" || !(collection = collection.trim())) {
        throw new Error("Invalid collection argument");
    }
    if (typeof identifier !== "string" || !(identifier = identifier.trim())) {
        throw new Error("Invalid identifier argument");
    }
    let baseUri;
    try {
        baseUri = new URL(identifier);
    }
    catch (e) {
        throw new Error(`Invalid ${collection} identifier: ${identifier}. Not a valid URI`);
    }
    // Path is of the form '/collection/name[/version]'
    const segments = (baseUri.pathname || "").split("/");
    if (segments.length !== 3 && segments.length !== 4) {
        throw new Error(`Invalid ${collection} identifier: ${identifier}. Bad number of segments: ${segments.length}`);
    }
    if (collection !== segments[1]) {
        throw new Error(`Invalid ${collection} identifier: ${identifier}. segment [1] should be "${collection}", found "${segments[1]}"`);
    }
    const vaultUrl = `${baseUri.protocol}//${baseUri.host}`;
    const name = segments[2];
    const version = segments.length === 4 ? segments[3] : undefined;
    return {
        vaultUrl,
        name,
        version,
    };
}

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
 * Common properties and methods of the Key Vault Secret Pollers.
 */
class KeyVaultSecretPoller extends coreLro.Poller {
    constructor() {
        super(...arguments);
        /**
         * Defines how much time the poller is going to wait before making a new request to the service.
         */
        this.intervalInMs = 2000;
    }
    /**
     * The method used by the poller to wait before attempting to update its operation.
     */
    async delay() {
        return coreUtil.delay(this.intervalInMs);
    }
}
/**
 * Common properties and methods of the Key Vault Secret Poller operations.
 */
// eslint-disable-next-next no-use-before-define
class KeyVaultSecretPollOperation {
    constructor(state, options = {}) {
        this.state = state;
        this.cancelMessage = "";
        if (options.cancelMessage) {
            this.cancelMessage = options.cancelMessage;
        }
    }
    /**
     * Meant to reach to the service and update the Poller operation.
     * @param options - The optional parameters, which is only an abortSignal from \@azure/abort-controller
     */
    async update() {
        throw new Error("Operation not supported.");
    }
    /**
     * Meant to reach to the service and cancel the Poller operation.
     * @param options - The optional parameters, which is only an abortSignal from \@azure/abort-controller
     */
    async cancel() {
        throw new Error(this.cancelMessage);
    }
    /**
     * Serializes the Poller operation.
     */
    toString() {
        return JSON.stringify({
            state: this.state,
        });
    }
}

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
 * Parses the given Key Vault Secret Id. An example is:
 *
 *   https://<keyvault-name>.vault.azure.net/secrets/<secret-name>/<unique-version-id>
 *
 * On parsing the above Id, this function returns:
 *```ts
 *   {
 *      sourceId: "https://<keyvault-name>.vault.azure.net/secrets/<secret-name>/<unique-version-id>",
 *      vaultUrl: "https://<keyvault-name>.vault.azure.net",
 *      version: "<unique-version-id>",
 *      name: "<secret-name>"
 *   }
 *```
 * @param id - The Id of the Key Vault Secret.
 */
function parseKeyVaultSecretIdentifier(id) {
    const urlParts = id.split("/");
    const collection = urlParts[3];
    return Object.assign({ sourceId: id }, parseKeyVaultIdentifier(collection, id));
}

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
 * @internal
 * Shapes the exposed {@link KeyVaultKey} based on either a received secret bundle or deleted secret bundle.
 */
function getSecretFromSecretBundle(bundle) {
    const secretBundle = bundle;
    const deletedSecretBundle = bundle;
    const parsedId = parseKeyVaultSecretIdentifier(secretBundle.id);
    const attributes = secretBundle.attributes;
    delete secretBundle.attributes;
    const resultObject = {
        value: secretBundle.value,
        name: parsedId.name,
        properties: {
            expiresOn: attributes === null || attributes === void 0 ? void 0 : attributes.expires,
            createdOn: attributes === null || attributes === void 0 ? void 0 : attributes.created,
            updatedOn: attributes === null || attributes === void 0 ? void 0 : attributes.updated,
            enabled: attributes === null || attributes === void 0 ? void 0 : attributes.enabled,
            notBefore: attributes === null || attributes === void 0 ? void 0 : attributes.notBefore,
            recoverableDays: attributes === null || attributes === void 0 ? void 0 : attributes.recoverableDays,
            recoveryLevel: attributes === null || attributes === void 0 ? void 0 : attributes.recoveryLevel,
            id: secretBundle.id,
            contentType: secretBundle.contentType,
            tags: secretBundle.tags,
            managed: secretBundle.managed,
            vaultUrl: parsedId.vaultUrl,
            version: parsedId.version,
            name: parsedId.name,
            certificateKeyId: secretBundle.kid,
        },
    };
    if (deletedSecretBundle.recoveryId) {
        resultObject.properties.recoveryId = deletedSecretBundle.recoveryId;
        resultObject.properties.scheduledPurgeDate = deletedSecretBundle.scheduledPurgeDate;
        resultObject.properties.deletedOn = deletedSecretBundle.deletedDate;
        resultObject.recoveryId = deletedSecretBundle.recoveryId;
        resultObject.scheduledPurgeDate = deletedSecretBundle.scheduledPurgeDate;
        resultObject.deletedOn = deletedSecretBundle.deletedDate;
    }
    if (attributes) {
        if (attributes.vaultUrl) {
            delete resultObject.properties.vaultUrl;
        }
        if (attributes.expires) {
            delete resultObject.properties.expires;
        }
        if (attributes.created) {
            delete resultObject.properties.created;
        }
        if (attributes.updated) {
            delete resultObject.properties.updated;
        }
    }
    return resultObject;
}

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
const SDK_VERSION = "4.8.0";

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
const tracingClient = coreTracing.createTracingClient({
    namespace: "Microsoft.KeyVault",
    packageName: "@azure/keyvault-secrets",
    packageVersion: SDK_VERSION,
});

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
 * An interface representing a delete secret's poll operation
 */
class DeleteSecretPollOperation extends KeyVaultSecretPollOperation {
    constructor(state, vaultUrl, client, operationOptions = {}) {
        super(state, { cancelMessage: "Canceling the deletion of a secret is not supported." });
        this.state = state;
        this.vaultUrl = vaultUrl;
        this.client = client;
        this.operationOptions = operationOptions;
    }
    /**
     * Sends a delete request for the given Key Vault Key's name to the Key Vault service.
     * Since the Key Vault Key won't be immediately deleted, we have {@link beginDeleteKey}.
     */
    deleteSecret(name, options = {}) {
        return tracingClient.withSpan("DeleteSecretPoller.deleteSecret", options, async (updatedOptions) => {
            const response = await this.client.deleteSecret(this.vaultUrl, name, updatedOptions);
            return getSecretFromSecretBundle(response);
        });
    }
    /**
     * The getDeletedSecret method returns the specified deleted secret along with its properties.
     * This operation requires the secrets/get permission.
     */
    getDeletedSecret(name, options = {}) {
        return tracingClient.withSpan("DeleteSecretPoller.getDeletedSecret", options, async (updatedOptions) => {
            const response = await this.client.getDeletedSecret(this.vaultUrl, name, updatedOptions);
            return getSecretFromSecretBundle(response);
        });
    }
    /**
     * Reaches to the service and updates the delete secret's poll operation.
     */
    async update(options = {}) {
        const state = this.state;
        const { name } = state;
        if (options.abortSignal) {
            this.operationOptions.abortSignal = options.abortSignal;
        }
        if (!state.isStarted) {
            const deletedSecret = await this.deleteSecret(name, this.operationOptions);
            state.isStarted = true;
            state.result = deletedSecret;
            if (!deletedSecret.properties.recoveryId) {
                state.isCompleted = true;
            }
        }
        if (!state.isCompleted) {
            try {
                state.result = await this.getDeletedSecret(name, this.operationOptions);
                state.isCompleted = true;
            }
            catch (error) {
                if (error.statusCode === 403) {
                    // At this point, the resource exists but the user doesn't have access to it.
                    state.isCompleted = true;
                }
                else if (error.statusCode !== 404) {
                    state.error = error;
                    state.isCompleted = true;
                    throw error;
                }
            }
        }
        return this;
    }
}

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
 * Class that creates a poller that waits until a secret finishes being deleted.
 */
class DeleteSecretPoller extends KeyVaultSecretPoller {
    constructor(options) {
        const { vaultUrl, client, name, operationOptions, intervalInMs = 2000, resumeFrom } = options;
        let state;
        if (resumeFrom) {
            state = JSON.parse(resumeFrom).state;
        }
        const operation = new DeleteSecretPollOperation(Object.assign(Object.assign({}, state), { name }), vaultUrl, client, operationOptions);
        super(operation);
        this.intervalInMs = intervalInMs;
    }
}

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
 * An interface representing a delete secret's poll operation
 */
class RecoverDeletedSecretPollOperation extends KeyVaultSecretPollOperation {
    constructor(state, vaultUrl, client, options = {}) {
        super(state, { cancelMessage: "Canceling the recovery of a deleted secret is not supported." });
        this.state = state;
        this.vaultUrl = vaultUrl;
        this.client = client;
        this.options = options;
    }
    /**
     * The getSecret method returns the specified secret along with its properties.
     * This operation requires the secrets/get permission.
     */
    getSecret(name, options = {}) {
        return tracingClient.withSpan("RecoverDeletedSecretPoller.getSecret", options, async (updatedOptions) => {
            const response = await this.client.getSecret(this.vaultUrl, name, options && options.version ? options.version : "", updatedOptions);
            return getSecretFromSecretBundle(response);
        });
    }
    /**
     * The recoverDeletedSecret method recovers the specified deleted secret along with its properties.
     * This operation requires the secrets/recover permission.
     */
    recoverDeletedSecret(name, options = {}) {
        return tracingClient.withSpan("RecoverDeletedSecretPoller.recoverDeletedSecret", options, async (updatedOptions) => {
            const response = await this.client.recoverDeletedSecret(this.vaultUrl, name, updatedOptions);
            return getSecretFromSecretBundle(response);
        });
    }
    /**
     * Reaches to the service and updates the delete secret's poll operation.
     */
    async update(options = {}) {
        const state = this.state;
        const { name } = state;
        if (options.abortSignal) {
            this.options.abortSignal = options.abortSignal;
        }
        if (!state.isStarted) {
            try {
                state.result = (await this.getSecret(name, this.options)).properties;
                state.isCompleted = true;
            }
            catch (_a) {
                // Nothing to do here.
            }
            if (!state.isCompleted) {
                state.result = (await this.recoverDeletedSecret(name, this.options)).properties;
                state.isStarted = true;
            }
        }
        if (!state.isCompleted) {
            try {
                state.result = (await this.getSecret(name, this.options)).properties;
                state.isCompleted = true;
            }
            catch (error) {
                if (error.statusCode === 403) {
                    // At this point, the resource exists but the user doesn't have access to it.
                    state.isCompleted = true;
                }
                else if (error.statusCode !== 404) {
                    state.error = error;
                    state.isCompleted = true;
                    throw error;
                }
            }
        }
        return this;
    }
}

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
 * Class that deletes a poller that waits until a secret finishes being deleted
 */
class RecoverDeletedSecretPoller extends KeyVaultSecretPoller {
    constructor(options) {
        const { vaultUrl, client, name, operationOptions, intervalInMs = 2000, resumeFrom } = options;
        let state;
        if (resumeFrom) {
            state = JSON.parse(resumeFrom).state;
        }
        const operation = new RecoverDeletedSecretPollOperation(Object.assign(Object.assign({}, state), { name }), vaultUrl, client, operationOptions);
        super(operation);
        this.intervalInMs = intervalInMs;
    }
}

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
 * The latest supported KeyVault service API version
 */
const LATEST_API_VERSION = "7.5";

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/// <reference lib="esnext.asynciterable" />
/**
 * The SecretClient provides methods to manage {@link KeyVaultSecret} in
 * the Azure Key Vault. The client supports creating, retrieving, updating,
 * deleting, purging, backing up, restoring and listing KeyVaultSecrets. The
 * client also supports listing {@link DeletedSecret} for a soft-delete enabled Azure
 * Key Vault.
 */
class SecretClient {
    /**
     * Creates an instance of SecretClient.
     *
     * Example usage:
     * ```ts
     * import { SecretClient } from "@azure/keyvault-secrets";
     * import { DefaultAzureCredential } from "@azure/identity";
     *
     * let vaultUrl = `https://<MY KEYVAULT HERE>.vault.azure.net`;
     * let credentials = new DefaultAzureCredential();
     *
     * let client = new SecretClient(vaultUrl, credentials);
     * ```
     * @param vaultUrl - The base URL to the vault. You should validate that this URL references a valid Key Vault resource. See https://aka.ms/azsdk/blog/vault-uri for details.
     * @param credential - An object that implements the `TokenCredential` interface used to authenticate requests to the service. Use the \@azure/identity package to create a credential that suits your needs.
     * @param pipelineOptions - Pipeline options used to configure Key Vault API requests.
     *                          Omit this parameter to use the default pipeline configuration.
     */
    constructor(vaultUrl, credential, pipelineOptions = {}) {
        this.vaultUrl = vaultUrl;
        const authPolicy = coreRestPipeline.bearerTokenAuthenticationPolicy({
            credential,
            scopes: [],
            challengeCallbacks: createKeyVaultChallengeCallbacks(pipelineOptions),
        });
        const internalPipelineOptions = Object.assign(Object.assign({}, pipelineOptions), { loggingOptions: {
                logger: logger.info,
                allowedHeaderNames: [
                    "x-ms-keyvault-region",
                    "x-ms-keyvault-network-info",
                    "x-ms-keyvault-service-version",
                ],
            } });
        this.client = new KeyVaultClient(pipelineOptions.serviceVersion || LATEST_API_VERSION, internalPipelineOptions);
        this.client.pipeline.addPolicy(authPolicy);
    }
    /**
     * The setSecret method adds a secret or secret version to the Azure Key Vault. If the named secret
     * already exists, Azure Key Vault creates a new version of that secret.
     * This operation requires the secrets/set permission.
     *
     * Example usage:
     * ```ts
     * let client = new SecretClient(url, credentials);
     * await client.setSecret("MySecretName", "ABC123");
     * ```
     * Adds a secret in a specified key vault.
     * @param secretName - The name of the secret.
     * @param value - The value of the secret.
     * @param options - The optional parameters.
     */
    setSecret(secretName, value, options = {}) {
        let unflattenedOptions = {};
        if (options) {
            const { enabled, notBefore, expiresOn: expires } = options, remainingOptions = tslib.__rest(options, ["enabled", "notBefore", "expiresOn"]);
            unflattenedOptions = Object.assign(Object.assign({}, remainingOptions), { secretAttributes: {
                    enabled,
                    notBefore,
                    expires,
                } });
        }
        return tracingClient.withSpan("SecretClient.setSecret", unflattenedOptions, async (updatedOptions) => {
            const response = await this.client.setSecret(this.vaultUrl, secretName, value, updatedOptions);
            return getSecretFromSecretBundle(response);
        });
    }
    /**
     * Deletes a secret stored in Azure Key Vault.
     * This function returns a Long Running Operation poller that allows you to wait indefinitely until the secret is deleted.
     *
     * This operation requires the secrets/delete permission.
     *
     * Example usage:
     * ```ts
     * const client = new SecretClient(url, credentials);
     * await client.setSecret("MySecretName", "ABC123");
     *
     * const deletePoller = await client.beginDeleteSecret("MySecretName");
     *
     * // Serializing the poller
     * const serialized = deletePoller.toString();
     *
     * // A new poller can be created with:
     * // const newPoller = await client.beginDeleteSecret("MySecretName", { resumeFrom: serialized });
     *
     * // Waiting until it's done
     * const deletedSecret = await deletePoller.pollUntilDone();
     * console.log(deletedSecret);
     * ```
     * Deletes a secret from a specified key vault.
     * @param secretName - The name of the secret.
     * @param options - The optional parameters.
     */
    async beginDeleteSecret(name, options = {}) {
        const poller = new DeleteSecretPoller(Object.assign(Object.assign({ name, client: this.client, vaultUrl: this.vaultUrl }, options), { operationOptions: options }));
        // This will initialize the poller's operation (the deletion of the secret).
        await poller.poll();
        return poller;
    }
    /**
     * The updateSecret method changes specified attributes of an existing stored secret. Properties that
     * are not specified in the request are left unchanged. The value of a secret itself cannot be
     * changed. This operation requires the secrets/set permission.
     *
     * Example usage:
     * ```ts
     * let secretName = "MySecretName";
     * let client = new SecretClient(url, credentials);
     * let secret = await client.getSecret(secretName);
     * await client.updateSecretProperties(secretName, secret.properties.version, { enabled: false });
     * ```
     * Updates the attributes associated with a specified secret in a given key vault.
     * @param secretName - The name of the secret.
     * @param secretVersion - The version of the secret.
     * @param options - The optional parameters.
     */
    async updateSecretProperties(secretName, secretVersion, options = {}) {
        let unflattenedOptions = {};
        if (options) {
            const { enabled, notBefore, expiresOn: expires } = options, remainingOptions = tslib.__rest(options, ["enabled", "notBefore", "expiresOn"]);
            unflattenedOptions = Object.assign(Object.assign({}, remainingOptions), { secretAttributes: {
                    enabled,
                    notBefore,
                    expires,
                } });
        }
        return tracingClient.withSpan("SecretClient.updateSecretProperties", unflattenedOptions, async (updatedOptions) => {
            const response = await this.client.updateSecret(this.vaultUrl, secretName, secretVersion, updatedOptions);
            return getSecretFromSecretBundle(response).properties;
        });
    }
    /**
     * The getSecret method is applicable to any secret stored in Azure Key Vault. This operation requires
     * the secrets/get permission.
     *
     * Example usage:
     * ```ts
     * let client = new SecretClient(url, credentials);
     * let secret = await client.getSecret("MySecretName");
     * ```
     * Get a specified secret from a given key vault.
     * @param secretName - The name of the secret.
     * @param options - The optional parameters.
     */
    getSecret(secretName, options = {}) {
        return tracingClient.withSpan("SecretClient.getSecret", options, async (updatedOptions) => {
            const response = await this.client.getSecret(this.vaultUrl, secretName, options && options.version ? options.version : "", updatedOptions);
            return getSecretFromSecretBundle(response);
        });
    }
    /**
     * The getDeletedSecret method returns the specified deleted secret along with its attributes.
     * This operation requires the secrets/get permission.
     *
     * Example usage:
     * ```ts
     * let client = new SecretClient(url, credentials);
     * await client.getDeletedSecret("MyDeletedSecret");
     * ```
     * Gets the specified deleted secret.
     * @param secretName - The name of the secret.
     * @param options - The optional parameters.
     */
    getDeletedSecret(secretName, options = {}) {
        return tracingClient.withSpan("SecretClient.getDeletedSecret", options, async (updatedOptions) => {
            const response = await this.client.getDeletedSecret(this.vaultUrl, secretName, updatedOptions);
            return getSecretFromSecretBundle(response);
        });
    }
    /**
     * The purge deleted secret operation removes the secret permanently, without the possibility of
     * recovery. This operation can only be enabled on a soft-delete enabled vault. This operation
     * requires the secrets/purge permission.
     *
     * Example usage:
     * ```ts
     * const client = new SecretClient(url, credentials);
     * const deletePoller = await client.beginDeleteSecret("MySecretName");
     * await deletePoller.pollUntilDone();
     * await client.purgeDeletedSecret("MySecretName");
     * ```
     * Permanently deletes the specified secret.
     * @param secretName - The name of the secret.
     * @param options - The optional parameters.
     */
    purgeDeletedSecret(secretName, options = {}) {
        return tracingClient.withSpan("SecretClient.purgeDeletedSecret", options, async (updatedOptions) => {
            await this.client.purgeDeletedSecret(this.vaultUrl, secretName, updatedOptions);
        });
    }
    /**
     * Recovers the deleted secret in the specified vault.
     * This function returns a Long Running Operation poller that allows you to wait indefinitely until the secret is recovered.
     *
     * This operation requires the secrets/recover permission.
     *
     * Example usage:
     * ```ts
     * const client = new SecretClient(url, credentials);
     * await client.setSecret("MySecretName", "ABC123");
     *
     * const deletePoller = await client.beginDeleteSecret("MySecretName");
     * await deletePoller.pollUntilDone();
     *
     * const recoverPoller = await client.beginRecoverDeletedSecret("MySecretName");
     *
     * // Serializing the poller
     * const serialized = recoverPoller.toString();
     *
     * // A new poller can be created with:
     * // const newPoller = await client.beginRecoverDeletedSecret("MySecretName", { resumeFrom: serialized });
     *
     * // Waiting until it's done
     * const deletedSecret = await recoverPoller.pollUntilDone();
     * console.log(deletedSecret);
     * ```
     * Recovers the deleted secret to the latest version.
     * @param secretName - The name of the deleted secret.
     * @param options - The optional parameters.
     */
    async beginRecoverDeletedSecret(name, options = {}) {
        const poller = new RecoverDeletedSecretPoller(Object.assign(Object.assign({ name, client: this.client, vaultUrl: this.vaultUrl }, options), { operationOptions: options }));
        // This will initialize the poller's operation (the recovery of the deleted secret).
        await poller.poll();
        return poller;
    }
    /**
     * Requests that a backup of the specified secret be downloaded to the client. All versions of the
     * secret will be downloaded. This operation requires the secrets/backup permission.
     *
     * Example usage:
     * ```ts
     * let client = new SecretClient(url, credentials);
     * let backupResult = await client.backupSecret("MySecretName");
     * ```
     * Backs up the specified secret.
     * @param secretName - The name of the secret.
     * @param options - The optional parameters.
     */
    backupSecret(secretName, options = {}) {
        return tracingClient.withSpan("SecretClient.backupSecret", options, async (updatedOptions) => {
            const response = await this.client.backupSecret(this.vaultUrl, secretName, updatedOptions);
            return response.value;
        });
    }
    /**
     * Restores a backed up secret, and all its versions, to a vault. This operation requires the
     * secrets/restore permission.
     *
     * Example usage:
     * ```ts
     * let client = new SecretClient(url, credentials);
     * let mySecretBundle = await client.backupSecret("MySecretName");
     * // ...
     * await client.restoreSecretBackup(mySecretBundle);
     * ```
     * Restores a backed up secret to a vault.
     * @param secretBundleBackup - The backup blob associated with a secret bundle.
     * @param options - The optional parameters.
     */
    restoreSecretBackup(secretBundleBackup, options = {}) {
        return tracingClient.withSpan("SecretClient.restoreSecretBackup", options, async (updatedOptions) => {
            const response = await this.client.restoreSecret(this.vaultUrl, secretBundleBackup, updatedOptions);
            return getSecretFromSecretBundle(response).properties;
        });
    }
    /**
     * Deals with the pagination of {@link listPropertiesOfSecretVersions}.
     * @param name - The name of the KeyVault Secret.
     * @param continuationState - An object that indicates the position of the paginated request.
     * @param options - Optional parameters for the underlying HTTP request.
     */
    listPropertiesOfSecretVersionsPage(secretName, continuationState, options = {}) {
        return tslib.__asyncGenerator(this, arguments, function* listPropertiesOfSecretVersionsPage_1() {
            if (continuationState.continuationToken == null) {
                const optionsComplete = Object.assign({ maxresults: continuationState.maxPageSize }, options);
                const currentSetResponse = yield tslib.__await(tracingClient.withSpan("SecretClient.listPropertiesOfSecretVersionsPage", optionsComplete, (updatedOptions) => this.client.getSecretVersions(this.vaultUrl, secretName, updatedOptions)));
                continuationState.continuationToken = currentSetResponse.nextLink;
                if (currentSetResponse.value) {
                    yield yield tslib.__await(currentSetResponse.value.map((bundle) => getSecretFromSecretBundle(bundle).properties));
                }
            }
            while (continuationState.continuationToken) {
                const currentSetResponse = yield tslib.__await(tracingClient.withSpan("SecretClient.listPropertiesOfSecretVersionsPage", options, (updatedOptions) => this.client.getSecretVersionsNext(this.vaultUrl, secretName, continuationState.continuationToken, updatedOptions)));
                continuationState.continuationToken = currentSetResponse.nextLink;
                if (currentSetResponse.value) {
                    yield yield tslib.__await(currentSetResponse.value.map((bundle) => getSecretFromSecretBundle(bundle).properties));
                }
                else {
                    break;
                }
            }
        });
    }
    /**
     * Deals with the iteration of all the available results of {@link listPropertiesOfSecretVersions}.
     * @param name - The name of the KeyVault Secret.
     * @param options - Optional parameters for the underlying HTTP request.
     */
    listPropertiesOfSecretVersionsAll(secretName, options = {}) {
        return tslib.__asyncGenerator(this, arguments, function* listPropertiesOfSecretVersionsAll_1() {
            var _a, e_1, _b, _c;
            const f = {};
            try {
                for (var _d = true, _e = tslib.__asyncValues(this.listPropertiesOfSecretVersionsPage(secretName, f, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) {
                    _c = _f.value;
                    _d = false;
                    const page = _c;
                    for (const item of page) {
                        yield yield tslib.__await(item);
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e));
                }
                finally { if (e_1) throw e_1.error; }
            }
        });
    }
    /**
     * Iterates all versions of the given secret in the vault. The full secret identifier and attributes are provided
     * in the response. No values are returned for the secrets. This operations requires the secrets/list permission.
     *
     * Example usage:
     * ```ts
     * let client = new SecretClient(url, credentials);
     * for await (const secretProperties of client.listPropertiesOfSecretVersions("MySecretName")) {
     *   const secret = await client.getSecret(secretProperties.name);
     *   console.log("secret version: ", secret);
     * }
     * ```
     * @param secretName - Name of the secret to fetch versions for.
     * @param options - The optional parameters.
     */
    listPropertiesOfSecretVersions(secretName, options = {}) {
        const iter = this.listPropertiesOfSecretVersionsAll(secretName, options);
        return {
            next() {
                return iter.next();
            },
            [Symbol.asyncIterator]() {
                return this;
            },
            byPage: (settings = {}) => this.listPropertiesOfSecretVersionsPage(secretName, settings, options),
        };
    }
    /**
     * Deals with the pagination of {@link listPropertiesOfSecrets}.
     * @param continuationState - An object that indicates the position of the paginated request.
     * @param options - Optional parameters for the underlying HTTP request.
     */
    listPropertiesOfSecretsPage(continuationState, options = {}) {
        return tslib.__asyncGenerator(this, arguments, function* listPropertiesOfSecretsPage_1() {
            if (continuationState.continuationToken == null) {
                const optionsComplete = Object.assign({ maxresults: continuationState.maxPageSize }, options);
                const currentSetResponse = yield tslib.__await(tracingClient.withSpan("SecretClient.listPropertiesOfSecretsPage", optionsComplete, (updatedOptions) => this.client.getSecrets(this.vaultUrl, updatedOptions)));
                continuationState.continuationToken = currentSetResponse.nextLink;
                if (currentSetResponse.value) {
                    yield yield tslib.__await(currentSetResponse.value.map((bundle) => getSecretFromSecretBundle(bundle).properties));
                }
            }
            while (continuationState.continuationToken) {
                const currentSetResponse = yield tslib.__await(tracingClient.withSpan("SecretClient.listPropertiesOfSecretsPage", options, (updatedOptions) => this.client.getSecretsNext(this.vaultUrl, continuationState.continuationToken, updatedOptions)));
                continuationState.continuationToken = currentSetResponse.nextLink;
                if (currentSetResponse.value) {
                    yield yield tslib.__await(currentSetResponse.value.map((bundle) => getSecretFromSecretBundle(bundle).properties));
                }
                else {
                    break;
                }
            }
        });
    }
    /**
     * Deals with the iteration of all the available results of {@link listPropertiesOfSecrets}.
     * @param options - Optional parameters for the underlying HTTP request.
     */
    listPropertiesOfSecretsAll(options = {}) {
        return tslib.__asyncGenerator(this, arguments, function* listPropertiesOfSecretsAll_1() {
            var _a, e_2, _b, _c;
            const f = {};
            try {
                for (var _d = true, _e = tslib.__asyncValues(this.listPropertiesOfSecretsPage(f, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) {
                    _c = _f.value;
                    _d = false;
                    const page = _c;
                    for (const item of page) {
                        yield yield tslib.__await(item);
                    }
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e));
                }
                finally { if (e_2) throw e_2.error; }
            }
        });
    }
    /**
     * Iterates the latest version of all secrets in the vault.  The full secret identifier and attributes are provided
     * in the response. No values are returned for the secrets. This operations requires the secrets/list permission.
     *
     * Example usage:
     * ```ts
     * let client = new SecretClient(url, credentials);
     * for await (const secretProperties of client.listPropertiesOfSecrets()) {
     *   const secret = await client.getSecret(secretProperties.name);
     *   console.log("secret: ", secret);
     * }
     * ```
     * List all secrets in the vault.
     * @param options - The optional parameters.
     */
    listPropertiesOfSecrets(options = {}) {
        const iter = this.listPropertiesOfSecretsAll(options);
        return {
            next() {
                return iter.next();
            },
            [Symbol.asyncIterator]() {
                return this;
            },
            byPage: (settings = {}) => this.listPropertiesOfSecretsPage(settings, options),
        };
    }
    /**
     * Deals with the pagination of {@link listDeletedSecrets}.
     * @param continuationState - An object that indicates the position of the paginated request.
     * @param options - Optional parameters for the underlying HTTP request.
     */
    listDeletedSecretsPage(continuationState, options = {}) {
        return tslib.__asyncGenerator(this, arguments, function* listDeletedSecretsPage_1() {
            if (continuationState.continuationToken == null) {
                const optionsComplete = Object.assign({ maxresults: continuationState.maxPageSize }, options);
                const currentSetResponse = yield tslib.__await(tracingClient.withSpan("SecretClient.listDeletedSecretsPage", optionsComplete, (updatedOptions) => this.client.getDeletedSecrets(this.vaultUrl, updatedOptions)));
                continuationState.continuationToken = currentSetResponse.nextLink;
                if (currentSetResponse.value) {
                    yield yield tslib.__await(currentSetResponse.value.map((bundle) => getSecretFromSecretBundle(bundle)));
                }
            }
            while (continuationState.continuationToken) {
                const currentSetResponse = yield tslib.__await(tracingClient.withSpan("SecretClient.lisDeletedSecretsPage", options, (updatedOptions) => this.client.getDeletedSecretsNext(this.vaultUrl, continuationState.continuationToken, updatedOptions)));
                continuationState.continuationToken = currentSetResponse.nextLink;
                if (currentSetResponse.value) {
                    yield yield tslib.__await(currentSetResponse.value.map((bundle) => getSecretFromSecretBundle(bundle)));
                }
                else {
                    break;
                }
            }
        });
    }
    /**
     * Deals with the iteration of all the available results of {@link listDeletedSecrets}.
     * @param options - Optional parameters for the underlying HTTP request.
     */
    listDeletedSecretsAll(options = {}) {
        return tslib.__asyncGenerator(this, arguments, function* listDeletedSecretsAll_1() {
            var _a, e_3, _b, _c;
            const f = {};
            try {
                for (var _d = true, _e = tslib.__asyncValues(this.listDeletedSecretsPage(f, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) {
                    _c = _f.value;
                    _d = false;
                    const page = _c;
                    for (const item of page) {
                        yield yield tslib.__await(item);
                    }
                }
            }
            catch (e_3_1) { e_3 = { error: e_3_1 }; }
            finally {
                try {
                    if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e));
                }
                finally { if (e_3) throw e_3.error; }
            }
        });
    }
    /**
     * Iterates the deleted secrets in the vault.  The full secret identifier and attributes are provided
     * in the response. No values are returned for the secrets. This operations requires the secrets/list permission.
     *
     * Example usage:
     * ```ts
     * let client = new SecretClient(url, credentials);
     * for await (const deletedSecret of client.listDeletedSecrets()) {
     *   console.log("deleted secret: ", deletedSecret);
     * }
     * ```
     * List all secrets in the vault.
     * @param options - The optional parameters.
     */
    listDeletedSecrets(options = {}) {
        const iter = this.listDeletedSecretsAll(options);
        return {
            next() {
                return iter.next();
            },
            [Symbol.asyncIterator]() {
                return this;
            },
            byPage: (settings = {}) => this.listDeletedSecretsPage(settings, options),
        };
    }
}

exports.SecretClient = SecretClient;
exports.logger = logger;
exports.parseKeyVaultSecretIdentifier = parseKeyVaultSecretIdentifier;
//# sourceMappingURL=index.js.map
