import { PayloadSerializer } from '../lib/transformers/PayloadSerializer.js';
import { hasBuffer } from '../Platform.js';
export class SerializablePayload {
    payload;
    payloadOptions;
    /**
     * The payload in its original format.
     * May not be populated when the `getPayload()` was not yet read.
     */
    _sourcePayload;
    /**
     * Sets the payload on the request.
     * This transforms the source `message` to its serialized form using the `PayloadSerializer`.
     *
     * @param message The payload value
     * @param mime The payload mime type. This is optional and sets the `payloadOptions.mime` value when set.
     */
    async writePayload(message, mime) {
        this._sourcePayload = message;
        this.payload = await PayloadSerializer.serialize(message);
        if (mime) {
            if (!this.payloadOptions) {
                this.payloadOptions = {};
            }
            this.payloadOptions.mime = mime;
        }
    }
    /**
     * Reads the payload as its original format.
     * It uses the `PayloadSerializer` to process the data.
     */
    async readPayload(as) {
        if (!this._sourcePayload) {
            this._sourcePayload = await PayloadSerializer.deserialize(this.payload, as);
        }
        return this._sourcePayload;
    }
    /**
     * Reads the payload as string, when it is possible.
     * This method assumes that the payload is a string regardless on the format of the data
     * (Buffer, ArrayBuffer, ...) and returns a string representation of the payload.
     *
     * @returns The string value of the payload of undefined if unable to process.
     */
    async readPayloadAsString() {
        const { payload } = this;
        if (!payload) {
            return undefined;
        }
        if (typeof payload === 'string') {
            return payload;
        }
        if (payload.type === 'string') {
            return payload.data;
        }
        if (['blob', 'file', 'formdata'].includes(payload.type)) {
            // should this return a string from the blob?
            return undefined;
        }
        const body = await this.readPayload();
        if (hasBuffer && body instanceof Buffer) {
            return body.toString();
        }
        const dataView = new DataView(body);
        const decoder = new TextDecoder();
        return decoder.decode(dataView);
    }
    toJSON() {
        const result = {};
        if (this.payload) {
            result.payload = this.payload;
        }
        if (this.payloadOptions) {
            result.payloadOptions = { ...this.payloadOptions };
        }
        return result;
    }
}
//# sourceMappingURL=SerializablePayload.js.map