var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import cloneDeep from 'lodash.clonedeep';
import { isMetaplexFile } from '../../storageModule';
import { useOperation, } from '../../../types';
import { walk } from '../../../utils';
// -----------------
// Operation
// -----------------
const Key = 'UploadMetadataOperation';
/**
 * Uploads a JSON Metadata object to the current storage provider.
 *
 * ```ts
 * const { uri } = await metaplex
 *   .nfts()
 *   .uploadMetadata({
 *     name: "My NFT",
 *     description: "My description",
 *     image: "https://arweave.net/123",
 *   };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
export const uploadMetadataOperation = useOperation(Key);
/**
 * @group Operations
 * @category Handlers
 */
export const uploadMetadataOperationHandler = {
    handle: (operation, metaplex, scope) => __awaiter(void 0, void 0, void 0, function* () {
        const rawMetadata = operation.input;
        const files = getAssetsFromJsonMetadata(rawMetadata);
        const assetUris = yield metaplex.storage().uploadAll(files);
        scope.throwIfCanceled();
        const metadata = replaceAssetsWithUris(rawMetadata, assetUris);
        const uri = yield metaplex.storage().uploadJson(metadata);
        return { uri, metadata, assetUris };
    }),
};
export const getAssetsFromJsonMetadata = (input) => {
    const files = [];
    walk(input, (next, value) => {
        if (isMetaplexFile(value)) {
            files.push(value);
        }
        else {
            next(value);
        }
    });
    return files;
};
export const replaceAssetsWithUris = (input, replacements) => {
    const clone = cloneDeep(input);
    let index = 0;
    walk(clone, (next, value, key, parent) => {
        if (isMetaplexFile(value) && index < replacements.length) {
            parent[key] = replacements[index++];
        }
        next(value);
    });
    return clone;
};
//# sourceMappingURL=uploadMetadata.js.map