/**
 * @packageDocumentation
 *
 * Adds libp2p functionality to Helia
 *
 * @example
 *
 * ```ts
 * import { createHelia } from 'helia'
 * import { withLibp2p } from '@helia/libp2p'
 *
 * const node = await withLibp2p(createHelia()).start()
 *
 * console.info(node.libp2p.peerId) // 12D3Koo...
 * ```
 */
import { NotStartedError } from '@libp2p/interface';
import { isLibp2p } from 'libp2p';
import { libp2pRouting } from "./routing.js";
import { createLibp2p } from "./utils/libp2p.js";
export { libp2pDefaults } from "./utils/libp2p-defaults.js";
async function getLibp2p(helia, opts) {
    if (isLibp2p(opts)) {
        return opts;
    }
    return createLibp2p(helia, {
        ...opts,
        dns: helia.dns,
        logger: helia.logger,
        datastore: helia.datastore
    });
}
export function withLibp2p(helia, opts) {
    let libp2p;
    // add a getter that informs the user they need to start Helia
    Object.defineProperty(helia, 'libp2p', {
        configurable: true,
        enumerable: true,
        get() {
            if (libp2p != null) {
                return libp2p;
            }
            throw new NotStartedError();
        }
    });
    const mixin = {
        name: 'libp2p',
        start: async (helia) => {
            if (libp2p == null) {
                libp2p = await getLibp2p(helia, opts);
            }
            try {
                if (!helia.hasRouter('libp2p-router')) {
                    helia.addRouter(libp2pRouting(libp2p));
                }
                if (isLibp2p(helia.libp2p)) {
                    // already configured libp2p
                    await helia.libp2p.start();
                }
            }
            catch (err) {
                if (err.name !== 'NotStartedError') {
                    throw err;
                }
            }
        },
        stop: async () => {
            await libp2p?.stop();
        }
    };
    helia.addMixin(mixin);
    // @ts-expect-error libp2p property is missing, even though we just defined it
    return helia;
}
//# sourceMappingURL=index.js.map