import axios from 'axios';
import { S3Client, } from '@aws-sdk/client-s3';
import { Upload } from '../utils/aws-lib-storage/index.js';
import { EventEmitter } from 'events';
export async function streamToBuffer(stream) {
    const accumulator = await new Response(stream).arrayBuffer();
    return Buffer.from(accumulator);
}
export class DecoratedReadableStream {
    constructor(byteLimit, underlyingSource) {
        this.stream = new ReadableStream(underlyingSource, { highWaterMark: byteLimit });
        const ee = new EventEmitter();
        this.on = ee.on;
        this.emit = ee.emit;
    }
    /**
     *
     * Dump the stream content to remote storage. This will consume the stream.
     * @param {string} fileName - the name of the remote file to write TDF ciphertext to.
     * @param {S3ClientConfig} [config] - the object containing remote storage configuration.
     * <br>A detailed spec for the interface can be found [here]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-s3/interfaces/s3clientconfig.html}
     * @param {string} [credentialURL] - the url to request remote storage credentials from.
     * @return {RemoteUploadResponse} - an object containing metadata for the uploaded file.
     */
    async toRemoteStore(fileName, config, credentialURL) {
        // State
        const CONCURRENT_UPLOADS = 6;
        const MAX_UPLOAD_PART_SIZE = 1024 * 1024 * 5; // 5MB
        let storageParams;
        let virtruTempS3Credentials;
        // Param validation
        if (!config) {
            try {
                virtruTempS3Credentials = await axios.get(credentialURL);
            }
            catch (e) {
                console.error(e);
            }
        }
        // Build a storage config object from 'config' or 'virtruTempS3Credentials'
        if (virtruTempS3Credentials) {
            const credentials = {
                accessKeyId: virtruTempS3Credentials.data.fields.AWSAccessKeyId,
                secretAccessKey: virtruTempS3Credentials.data.fields.AWSSecretAccessKey,
                sessionToken: virtruTempS3Credentials.data.fields.AWSSessionToken,
            };
            storageParams = {
                credentials,
                region: virtruTempS3Credentials.data.url.split('.')[1],
                forcePathStyle: false,
                maxAttempts: 3,
                useAccelerateEndpoint: true,
            };
        }
        else {
            storageParams = config;
        }
        const BUCKET_NAME = config?.Bucket || virtruTempS3Credentials?.data?.bucket || undefined;
        const FILE_NAME = fileName || 'upload.tdf';
        const s3 = new S3Client(storageParams);
        // Managed Parallel Upload
        const uploadParams = {
            Bucket: BUCKET_NAME,
            Key: FILE_NAME,
            Body: this.stream,
        };
        try {
            const parallelUpload = new Upload({
                client: s3,
                queueSize: CONCURRENT_UPLOADS,
                partSize: MAX_UPLOAD_PART_SIZE,
                leavePartsOnError: false,
                params: uploadParams,
            });
            parallelUpload.on('httpUploadProgress', (progress) => {
                this.emit('progress', progress);
            });
            return await parallelUpload.done();
        }
        catch (e) {
            console.error(e);
            throw e;
        }
    }
    async getMetadata() {
        return new Promise((resolve, reject) => {
            if (this.metadata) {
                resolve(this.metadata);
            }
            else {
                this.on('error', reject);
                this.on('rewrap', (rewrapResponse) => {
                    this.metadata = rewrapResponse;
                    resolve(rewrapResponse);
                });
            }
        });
    }
    /**
     * Dump the stream content to a buffer. This will consume the stream.
     * @return the plaintext in Buffer form.
     */
    async toBuffer() {
        return streamToBuffer(this.stream);
    }
    /**
     * Dump the stream content to a string. This will consume the stream.
     * @return the plaintext in string form.
     */
    async toString() {
        return new Response(this.stream).text();
    }
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiRGVjb3JhdGVkUmVhZGFibGVTdHJlYW0uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi90ZGYzL3NyYy9jbGllbnQvRGVjb3JhdGVkUmVhZGFibGVTdHJlYW0udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxLQUFLLE1BQU0sT0FBTyxDQUFDO0FBQzFCLE9BQU8sRUFHTCxRQUFRLEdBQ1QsTUFBTSxvQkFBb0IsQ0FBQztBQUU1QixPQUFPLEVBQUUsTUFBTSxFQUFFLE1BQU0sZ0NBQWdDLENBQUM7QUFJeEQsT0FBTyxFQUFFLFlBQVksRUFBRSxNQUFNLFFBQVEsQ0FBQztBQUd0QyxNQUFNLENBQUMsS0FBSyxVQUFVLGNBQWMsQ0FBQyxNQUFrQztJQUNyRSxN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