"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.rethrowErrorWithSourceActionName = exports.lowercaseRequestidFromLogstoreMetadata = exports.tapDebugComplete = exports.nodeAddressFromUrl = void 0;
const rxjs_1 = require("rxjs");
const nodeAddressFromUrl = (url, nodeManager) => (0, rxjs_1.defer)(() => nodeManager.getNodeAddressFromUrl(url)).pipe(
// should error if completed without a value.
(0, rxjs_1.first)(Boolean), (0, rxjs_1.share)());
exports.nodeAddressFromUrl = nodeAddressFromUrl;
function tapDebugComplete(name) {
    return (0, rxjs_1.tap)({
        complete: () => console.log(`COMPLETE ${name}`),
        unsubscribe: () => console.log(`UNSUBSCRIBE ${name}`),
        error: (err) => console.log(`ERROR ${name}`, err),
        finalize: () => console.log(`FINALIZE ${name}`),
        subscribe: () => console.log(`SUBSCRIBE ${name}`),
        next: (value) => {
            console.log(`NEXT ${name}`, value);
        },
    });
}
exports.tapDebugComplete = tapDebugComplete;
function lowercaseRequestidFromLogstoreMetadata(stream) {
    return stream.pipe((0, rxjs_1.map)((m) => m.requestId), 
    // should error if completed without a value.
    (0, rxjs_1.filter)((val) => !!val), (0, rxjs_1.first)(), rethrowErrorWithSourceActionName(`getting request id from logstore stream`), (0, rxjs_1.map)((val) => val.toLowerCase()), (0, rxjs_1.shareReplay)({
        refCount: true,
        bufferSize: 1,
    }));
}
exports.lowercaseRequestidFromLogstoreMetadata = lowercaseRequestidFromLogstoreMetadata;
function rethrowErrorWithSourceActionName(actionName) {
    return (0, rxjs_1.catchError)((error) => {
        const originalMessage = 'message' in error
            ? error.message
            : typeof error === 'string'
                ? error
                : '';
        return (0, rxjs_1.throwError)(() => 
        // we don't want to add the action name if it's already there, to preserve the original source
        originalMessage.startsWith('Error while')
            ? error
            : new Error(`Error while ${actionName}: ${originalMessage}`));
    });
}
exports.rethrowErrorWithSourceActionName = rethrowErrorWithSourceActionName;
//# sourceMappingURL=utils.js.map